🚀 LeetCode Day Problem Solving 🚀 Day-89 📌 Problem: Given a binary string s, determine whether you can reach the last index starting from index 0. 👉 You can jump from index i to any index j such that: ✔ i + minJump <= j <= i + maxJump ✔ s[j] == '0' 🧠 Example 1: Input: s = "011010" minJump = 2 maxJump = 3 ✅ Output: true 🔄 Possible Path: 0 → 3 → 5 ✔ Both positions contain '0' 🧠 Example 2: Input: s = "01101110" minJump = 2 maxJump = 3 ❌ Output: false ✔ No valid sequence of jumps can reach the last index. 💡 Key Insight (Very Important 🔥): 👉 From each index, checking every possible jump directly would be too slow ❌ Because: ⚠ Worst case becomes O(n²) ⚡ Optimization Idea: ✔ Use BFS + Sliding Window Instead of repeatedly checking the same range: ✅ Maintain how far we have already processed. This avoids duplicate work. ⚡ Core Idea: For every reachable index i: ✔ Explore indices in range: [i + minJump , i + maxJump] ✔ Only visit positions containing '0' ✔ Avoid revisiting indices 🔥 Why Sliding Window Helps? Without optimization: 👉 Same indices get scanned many times. With sliding window: ✅ Every index is processed only once. So complexity becomes linear. ⚡ Algorithm: 1️⃣ Start BFS from index 0 2️⃣ For every current index: ✔ Compute jump range 3️⃣ Traverse only unvisited positions 4️⃣ If last index is reached → return true 5️⃣ If BFS ends → return false 📊 Complexity Analysis: ⏱ Time Complexity: O(n) 📦 Space Complexity: O(n) 🧠 What I Learned: ✔ BFS on arrays ✔ Sliding window optimization ✔ Efficient range traversal ✔ Avoiding repeated computations ✅ Day 89 Completed 🚀 Improving in Graphs + BFS + Sliding Window 💪 #Leetcode #coding #learning #CodingChallenge #ProblemSolving #DSA #BFS #SlidingWindow #Graphs #Optimization #MilanSahoo 🚀
Milan Sahoo’s Post
More Relevant Posts
-
🚀 #LeetCode Day Problem Solving 🚀 Day-68 📌 Problem: Given a binary string s, determine whether you can reach the last index starting from index 0. 👉 You can jump from index i to any index j such that: ✔ i + minJump <= j <= i + maxJump ✔ s[j] == '0' 🧠 Example 1: Input: s = "011010" minJump = 2 maxJump = 3 ✅ Output: true 🔄 Possible Path: 0 → 3 → 5 ✔ Both positions contain '0' 🧠 Example 2: Input: s = "01101110" minJump = 2 maxJump = 3 ❌ Output: false ✔ No valid sequence of jumps can reach the last index. 💡 Key Insight (Very Important 🔥): 👉 From each index, checking every possible jump directly would be too slow ❌ Because: ⚠ Worst case becomes O(n²) ⚡ Optimization Idea: ✔ Use BFS + Sliding Window Instead of repeatedly checking the same range: ✅ Maintain how far we have already processed. This avoids duplicate work. ⚡ Core Idea: For every reachable index i: ✔ Explore indices in range: [i + minJump , i + maxJump] ✔ Only visit positions containing '0' ✔ Avoid revisiting indices 🔥 Why Sliding Window Helps? Without optimization: 👉 Same indices get scanned many times. With sliding window: ✅ Every index is processed only once. So complexity becomes linear. ⚡ Algorithm: 1️⃣ Start BFS from index 0 2️⃣ For every current index: ✔ Compute jump range 3️⃣ Traverse only unvisited positions 4️⃣ If last index is reached → return true 5️⃣ If BFS ends → return false 📊 Complexity Analysis: ⏱ Time Complexity: O(n) 📦 Space Complexity: O(n) 🧠 What I Learned: ✔ BFS on arrays ✔ Sliding window optimization ✔ Efficient range traversal ✔ Avoiding repeated computations ✅ Day 68 Completed 🚀 Improving in Graphs + BFS + Sliding Window 💪 #Leetcode #coding #learning #CodingChallenge #ProblemSolving #DSA #BFS #SlidingWindow #Graphs #Optimization
To view or add a comment, sign in
-
-
🚀 Day 52 of 100 Days LeetCode Challenge Problem: Minimize Hamming Distance After Swap Operations Day 52 is a powerful Graph + Union Find (DSU) + Frequency Matching problem 🔥 💡 Key Insight: Allowed swaps create connected components. 👉 Any indices within the same connected component can be rearranged freely. So instead of individual swaps: ⚡ Think in terms of groups of interchangeable indices 🔍 Core Approach: 1️⃣ Build Connected Components Use Disjoint Set Union (DSU / Union Find) For every allowed swap [a, b]: union(a, b) 👉 All connected indices belong to the same group 2️⃣ Group Source Values For each component: Count frequencies of values in source Example: component → {1:2, 3:1} 3️⃣ Match with Target Traverse target values in same component If value exists in frequency map: Decrease count ✅ Else: Hamming distance increases ❌ 💡 Why This Works: Inside a connected component: 👉 We can permute values however we want So the goal becomes: Maximize matches within each component 🔥 Time Complexity: Efficient with: DSU + HashMap 🔥 What I Learned Today: Swap operations often imply graph connectivity DSU is extremely powerful for grouping problems Frequency matching helps minimize mismatches optimally 📈 Challenge Progress: Day 52/100 ✅ Strong consistency continues! LeetCode, Union Find, DSU, Graph Theory, HashMap, Arrays, Optimization, DSA Practice, Problem Solving #100DaysOfCode #LeetCode #DSA #CodingChallenge #UnionFind #GraphTheory #Hashing #ProblemSolving #TechJourney #ProgrammerLife #SoftwareDeveloper #CodingLife #LearnToCode #Developers #Consistency #GrowthMindset #InterviewPrep
To view or add a comment, sign in
-
-
🚀 Day 57 of 100 Days LeetCode Challenge Problem: Detect Cycles in 2D Grid Day 57 is a classic Graph Traversal + DFS/BFS cycle detection problem 🔥 💡 Key Insight: The grid behaves like a graph: Each cell = node Adjacent same-valued cells = edges We need to detect: 👉 A cycle of length ≥ 4 🔍 Core Approach (DFS): 1️⃣ Traverse Every Cell If not visited: Start DFS/BFS 2️⃣ Move Only to Same Characters Allowed directions: ⬆️ ⬇️ ⬅️ ➡️ Condition: grid[nx][ny] == grid[x][y] 3️⃣ Track Previous Cell Important rule: 👉 We cannot immediately return to the parent node So during DFS: Store previous position (px, py) 4️⃣ Cycle Detection Condition If: Neighbor already visited AND not the parent ✅ Cycle found 💡 Why Length ≥ 4 Works Automatically: In grid DFS: Revisiting a non-parent visited node guarantees a valid cycle 🔥 Alternative Solution: BFS with parent tracking also works 🔥 What I Learned Today: Grid problems are often hidden graph problems Parent tracking is crucial in cycle detection DFS patterns are reusable across many graph questions 📈 Challenge Progress: Day 57/100 ✅ Advanced graph problems unlocked! LeetCode, Graph Theory, DFS, BFS, Cycle Detection, Matrix Traversal, Grid Problems, DSA Practice, Problem Solving #100DaysOfCode #LeetCode #DSA #CodingChallenge #GraphTheory #DFS #BFS #CycleDetection #ProblemSolving #TechJourney #ProgrammerLife #SoftwareDeveloper #CodingLife #LearnToCode #Developers #Consistency #GrowthMindset #InterviewPrep
To view or add a comment, sign in
-
-
🚀 LeetCode Day Problem Solving 🚀 Day-65 📌 Problem: Given an array nums[] 🎯 Define rotation function: 👉 Rotate array k times → arrₖ 👉 Compute: F(k) = 0*arrₖ[0] + 1*arrₖ[1] + ... + (n-1)*arrₖ[n-1] 🎯 Goal: Find the maximum value among all F(k) 🧠 Example: Input: nums = [4,3,2,6] ✅ Output: 26 💡 Key Insight (Most Important 🔥): ✔ Brute force rotation = ❌ O(n²) (too slow) 👉 Instead, use relation between consecutive rotations ⚡ Core Formula: F(k) = F(k-1) + sum(nums) - n \cdot nums[n-k] 🔥 Meaning: ✔ We can compute next rotation using previous one ✔ No need to recompute from scratch ⚡ Approach: 1️⃣ Compute: sum = total sum of array F(0) 2️⃣ Iterate k = 1 → n-1: Use formula to compute F(k) 3️⃣ Track maximum value ⚡ Why it works? ✔ Each rotation shifts elements ✔ Contribution changes in a predictable way 👉 That’s why recurrence works 🚀 📊 Complexity Analysis: ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) 🧠 What I Learned: ✔ Turning brute force → optimized using math ✔ Rotation problems often have hidden patterns ✔ Importance of deriving recurrence relations ✅ Day 65 Completed 🚀 Leveling up in Array + Mathematical Optimization 💪 #Leetcode #DSA #ProblemSolving #BitManipulation #CodingJourney #InterviewPreparation #Consistency #MilanSahoo 🚀
To view or add a comment, sign in
-
-
#Day145 of #365DaysOfCode Solved an interesting Mathematical + Pattern Observation problem today Today’s problem: **672. Bulb Switcher II** 🔷 Problem Summary There are `n` bulbs initially turned ON and 4 different buttons that flip bulbs in different patterns. Goal 👇 Find the number of different possible bulb states after performing exactly `presses` operations. 💡 Core Idea Instead of simulating all bulbs: ✅ Observe repeating patterns ✅ Reduce the problem mathematically ✅ Focus only on first 3 bulbs Why? Because after bulb 3, the flipping patterns start repeating. 🧠 Important Insight The number of unique states depends only on: • Small values of `n` • Number of button presses Key observation: 👉 Maximum unique patterns stabilize quickly So we handle cases directly: ✅ `presses == 0 → 1 state` ✅ `n == 1 → 2 states` ✅ `n == 2 → 3 or 4 states` ✅ `n >= 3 → maximum 8 states` This converts a seemingly huge simulation problem into simple case analysis ⚡ Complexity • Time: O(1) • Space: O(1) What I Learned Today Today’s problem showed how powerful pattern observation can be. Main takeaways: ✅ Mathematical simplification ✅ Pattern repetition ✅ State reduction ✅ Case-based optimization Sometimes the best solution is not simulation — it’s recognizing hidden patterns #LeetCode #DSA #Java #Math #Patterns #BitManipulation #ProblemSolving #CodingJourney #SoftwareEngineering #365DaysOfCode
To view or add a comment, sign in
-
-
🚀 #LeetCode Day Problem Solving 🚀 Day-45 📌 Problem: Given an array nums[] 🎯 Define rotation function: 👉 Rotate array k times → arrₖ 👉 Compute: F(k) = 0*arrₖ[0] + 1*arrₖ[1] + ... + (n-1)*arrₖ[n-1] 🎯 Goal: Find the maximum value among all F(k) 🧠 Example: Input: nums = [4,3,2,6] ✅ Output: 26 💡 Key Insight (Most Important 🔥): ✔ Brute force rotation = ❌ O(n²) (too slow) 👉 Instead, use relation between consecutive rotations ⚡ Core Formula: F(k) = F(k-1) + sum(nums) - n \cdot nums[n-k] 🔥 Meaning: ✔ We can compute next rotation using previous one ✔ No need to recompute from scratch ⚡ Approach: 1️⃣ Compute: sum = total sum of array F(0) 2️⃣ Iterate k = 1 → n-1: Use formula to compute F(k) 3️⃣ Track maximum value ⚡ Why it works? ✔ Each rotation shifts elements ✔ Contribution changes in a predictable way 👉 That’s why recurrence works 🚀 📊 Complexity Analysis: ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) 🧠 What I Learned: ✔ Turning brute force → optimized using math ✔ Rotation problems often have hidden patterns ✔ Importance of deriving recurrence relations ✅ Day 45 Completed 🚀 Leveling up in Array + Mathematical Optimization 💪 #Leetcode #DSA #ProblemSolving #BitManipulation #CodingJourney #InterviewPreparation #Consistency
To view or add a comment, sign in
-
-
🚀 Day 12 of Consistent Problem Solving Today I worked on a problem that looks simple — but exposes a very common mistake in tree problems. 📌 Problem: Find the minimum depth of a binary tree (shortest path from root to a leaf node). ⚠️ Key Detail: A leaf node must have both children NULL — missing this leads to incorrect solutions. 🧪 My Initial Approach (Naive DFS): I tried: 1 + min(leftDepth, rightDepth) But this fails when one child is NULL. 👉 Example: If one side is missing, its depth becomes 0, and min() incorrectly picks it. ❌ This treats a non-existent path as valid. ⚡ Key Insight: If one child is NULL, we must ignore that side completely. 💡 Correct DFS Approach: If one subtree is missing → go through the other Only take min() when both children exist Time Complexity: O(n) Space Complexity: O(h) (recursion stack) 🚀 Better Approach (BFS — Interview Favorite): Use level-order traversal: Traverse level by level The first leaf node encountered → answer 👉 This works because we are looking for the shortest path Time Complexity: O(n) Space Complexity: O(w) 🧩 Key Learning: “Minimum / shortest path” → think BFS first DFS requires careful handling of NULL cases Edge cases define correctness in tree problems ⚠️ Common Pitfalls: Blindly using min(left, right) Misunderstanding leaf node definition Ignoring skewed tree cases 🔗 Follow-up Insight: This pattern appears in: Maximum Depth of Binary Tree Binary Tree Level Order Traversal Nearest leaf / shortest path problems 📚 Prerequisites: Tree traversal (DFS & BFS) Recursion basics Queue-based traversal 💬 One-line intuition: “Minimum depth = first leaf you encounter in level-order traversal.” Consistency + correctness = real growth 📈 Do you prefer DFS or BFS for tree problems like this? 👇 #LeetCode #BinaryTree #BFS #DFS #Algorithms #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
📌 Strengthening DSA Concepts through Tree Traversals Recently, I solved LeetCode 199 – Binary Tree Right Side View using DFS (Depth-First Search). At first glance, it seems simple… But the real thinking? 👉 How do we ensure we capture only the rightmost node at each level? 👉 How do we avoid storing unnecessary nodes? 🔍 Problem Given the root of a binary tree, return the nodes visible from the right side, ordered from top to bottom. In simple terms: 👉 Imagine standing on the right side of the tree 👉 Return the first visible node at every level 🧠 Key Insight To solve this efficiently: 👉 Use DFS traversal 👉 Traverse Right → Left 👉 Track the current level 👉 Store the first node encountered at each level Why this works? Because when we visit: 👉 Right subtree first 👉 The rightmost node at each level is processed before others ⚙️ Core Logic 👉 Maintain a list lt 👉 If level == lt.size() ✔ It means this level hasn’t been visited yet ✔ Add current node 👉 Recursively call: Right child first Then Left child This ensures: ✔ Rightmost nodes are captured ✔ No extra data structure needed 🧩 Technique Used 👉 DFS (Preorder Style) 👉 Level Tracking 👉 Recursive Tree Traversal 👉 Space Optimization ⏱️ Time Complexity 👉 O(n) Each node is visited once. Space Complexity: 👉 O(h) Where h = height of tree (recursion stack) ⚡ Why This Approach Is Powerful Instead of using BFS or queues… We leverage: 👉 Controlled traversal order 👉 Level-based condition 👉 Clean recursive logic This problem strengthens understanding of: ✔ Tree traversal patterns ✔ Recursion depth control ✔ Level-based problem solving #DSA #BinaryTree #Recursion #TreeTraversal #LeetCode #ProblemSolving #CodingInterview #100DaysOfCode
To view or add a comment, sign in
-
🚀 LeetCode — 1631. Path With Minimum Effort Solved | Medium | Graph | Dijkstra Algorithm | Matrix Traversal 🔗 Solution Link: https://lnkd.in/gay9gF9M This problem was genuinely difficult for me at first because I was struggling with one thing: “How do we even apply Dijkstra on a matrix instead of a graph?” 🤔 I was too used to adjacency lists and graph nodes, so seeing Dijkstra inside a grid felt confusing initially. But after spending time thinking about it, the important realization clicked: A matrix is also a graph. Each cell simply acts like a node with 4 possible neighbors. 💡 Core Idea The effort of a path is NOT the sum of costs. Instead: Path effort = maximum absolute height difference encountered along the route. So while moving to a neighbor: newEffort = max(currentEffort, abs(heightDifference)) And we want to minimize this maximum effort. 🧠 Approach (Modified Dijkstra) Use a priority queue storing: (currentEffort, row, col) Traverse using a direction array: up, down, left, right For every neighbor: calculate the new maximum effort If: newEffort < distance[nr][nc] update distance and push into priority queue Return immediately when reaching the bottom-right cell The biggest learning from this problem was understanding that Dijkstra is not limited to traditional graphs — grids/matrices can also be modeled as graphs very naturally. 📈 Complexity Time: O((rows * cols) log(rows * cols)) Space: O(rows * cols) A very beautiful problem that changes how you think about graphs inside matrices. #LeetCode #Dijkstra #Graphs #MatrixTraversal #ShortestPath #DSA #Algorithms #CompetitiveProgramming #ProblemSolving #CodingJourney #SoftwareEngineering #GraphTheory #Programming #Developers #LearningInPublic
To view or add a comment, sign in
-
-
🚀 #LeetCode Day Problem Solving 🚀 Day-67 📌 Problem: Given an array arr[] and an integer d. From index i, you can jump: 👉 Left or Right up to distance d But only if: ✔ arr[i] > arr[j] ✔ Every element between i and j is also smaller than arr[i] Find the maximum number of indices you can visit. 🧠 Example: Input: arr = [6,4,14,6,8,13,9,7,10,6,12] d = 2 ✅ Output: 4 💡 Key Insight (Very Important 🔥): 👉 From every index, we try all valid jumps But many paths repeat again and again ❌ So we use: ✔ DFS ✔ Memoization (DP) to store already computed answers. ⚡ Core Idea: Let: dp[i] = maximum indices visitable starting from index i For every index: ✔ Try jumping left ✔ Try jumping right ✔ Stop when: distance exceeds d a higher/equal element blocks the path 🔥 Important Observation: You can jump only to strictly smaller values. And once a larger/equal value appears in between: ❌ further jumping in that direction is impossible. ⚡ How DFS Works: From each index: 1️⃣ Explore all valid left jumps 2️⃣ Explore all valid right jumps 3️⃣ Take maximum path length among them 4️⃣ Store result in DP array 🧠 Example Flow: Starting from index 10 → value 12 Possible path: 10 → 8 → 6 → 7 Values: 12 → 10 → 9 → 7 Total visited indices = 4 ⚡ Why Memoization Helps? Without memoization: ❌ Same states recomputed many times With memoization: ✔ Each index solved once only Huge optimization 🚀 📊 Complexity Analysis: ⏱ Time Complexity: O(n × d) 📦 Space Complexity: O(n) 🧠 What I Learned: ✔ DFS + DP optimization ✔ Recursive state caching ✔ Valid jump constraints handling ✔ Breaking conditions in traversal ✔ Graph-style thinking on arrays ✅ Day 67 Completed 🚀 Improving in Dynamic Programming & DFS Problems 💪 #Leetcode #DSA #ProblemSolving #BitManipulation #CodingJourney #InterviewPreparation #Consistency
To view or add a comment, sign in
-