DSA Series ... 🚀 Two pointers approach (Last problem) Leetcode #42 (Level: Hard) Trapping Rain Water ... 🎯 Problem : Given an elevation map (the bars), calculate how much rainwater can be trapped between the "peaks". Working Principle ... 🧐 Simply take it as two walls for easy to understand, moving inward from the left and right sides. ** Pointers: Start one pointer at the very beginning (left) and one at the end (right). ** ** leftMax and rightMax for bottleneck ** ** trappedWater to hold water level values ** - By maintaining leftMax and rightMax variables and moving inward from both ends of the array, we can calculate the trapped water in a single pass. - If height[left] is smaller than height[right], we know the water level is bounded by the left side. So compare the height[left] with leftMax. * If it is greater than max value, replace leftMax value, otherwise add water level with trappedWater by minus max with current height. * Then move (Increase) the left pointer. - If height[right] is smaller than height[left], compare the height[right] with rightMax. * If it is greater than max value, replace rightMax value, otherwise add water level with trappedWater by minus max with current height. * Then move (Decrease) the right pointer. - If there is overtaken with left and right pointers, terminate the loop and return trappedWater. That's all ... 😎 * Time Complexity: O(n) - We only pass through the array once. * Space Complexity: O(1) - No extra arrays needed, just a few variables. Get in touch : ) ... 🚀 I'll see you all in next post(Chapter) that was about another approach in DSA "Sliding Window"... 🔥 If you have any suggestions or questions, comment or ping me ... 💬 #Java #CodingInterview #Algorithms #LeetCode #SoftwareEngineering #DataStructures #DSA #TwoPointers #TrappingRainWater
Jeyaseelan Inbaraj’s Post
More Relevant Posts
-
🔥 Day 331 – Daily DSA Challenge! 🔥 Problem: 🟦 Perfect Squares Given an integer n, return the least number of perfect square numbers that sum to n. Example: 12 = 4 + 4 + 4 → answer = 3 13 = 4 + 9 → answer = 2 💡 Key Insight — Classic DP (Unbounded Knapsack Style) We build the solution bottom-up. For each number i, try subtracting every possible perfect square j² ≤ i. Core recurrence: Where: j² is any perfect square ≤ i +1 represents using that square 🧠 Why This Works 🔹 Every number can be represented as sum of 1² repeated → worst case = i 🔹 We iteratively improve this by checking larger squares 🔹 This is similar to coin change problem Coins = perfect squares Target = n ⚡ Optimized Plan: ✅ Create dp[n+1] ✅ Initialize dp[i] = i (worst case: all 1’s) ✅ For each i: Try every square j² ≤ i Update minimum ✅ Return dp[n] ✅ Time Complexity: O(n √n) ✅ Space Complexity: O(n) 💬 Challenge for you: 1️⃣ Can this be solved using BFS instead of DP? 2️⃣ How does Lagrange’s Four Square Theorem relate to this problem? 3️⃣ Can we optimize by precomputing squares only once? #DSA #Day331 #LeetCode #DynamicProgramming #Math #PerfectSquares #Java #ProblemSolving #KeepCoding #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 DSA Daily Challenge – Day 17: Container With Most Water (Medium) 🧠 Another classic two-pointer problem from LeetCode 11 — perfect for understanding pointer optimization and maximizing area. 🔍 Problem Recap You’re given an array height representing vertical lines on the x-axis. We need to find two lines that, together with the x-axis, form a container containing the most water. Width = distance between two lines Height = minimum of the two lines Area = width × height 💡 Core Idea Instead of brute force O(n²), we can optimize using two pointers: 1️⃣ Initialize leftPtr = 0 and rightPtr = height.length - 1 2️⃣ Calculate area: width = rightPtr - leftPtr height = min(height[leftPtr], height[rightPtr]) area = width * height 3️⃣ Update maxWater if area is larger 4️⃣ Move pointers intelligently: If left < right → move left forward If right < left → move right backward If equal → move both This ensures we maximize height while reducing width smartly. 🧠 Why This Works Brute force checks every pair → O(n²) ❌ Two-pointer approach → O(n) ✅ Always moving the shorter line is key: Moving the taller line cannot increase area Moving the shorter line may find a taller one 🧩 Dry Run Example Array: [1,8,6,2,5,4,8,3,7] Start: left=1, right=7 → area = min(1,7)*8 = 8 Move left → height=8 → area = min(8,7)*7 = 49 ✅ Continue adjusting → max area = 49 ⚡ Pattern Connection Two-pointer optimization Maximizing/minimizing with math insight No extra space → O(1) space Very common in array and sliding window problems #DSA #LeetCode #Day17 #Java #TwoPointers #Arrays #CodingInterview #ProblemSolving #100DaysOfCode #DataStructures #InterviewPrep #Algorithm #MediumLevel #ProgrammingTips #CodingChallenge #MaxArea #ContainerWithMostWater #OptimizedCode #PointerTechniques
To view or add a comment, sign in
-
-
🔥 Day 336 – Daily DSA Challenge! 🔥 Problem: 🎯 Combination Sum III Find all valid combinations of k numbers that sum up to n, such that: Only numbers 1 through 9 are used Each number is used at most once No duplicate combinations 💡 Key Insight — Controlled Backtracking This is a constrained combination problem with: Fixed size → k numbers Fixed sum → n Limited choices → 1 to 9 No repetition We explore combinations in increasing order to avoid duplicates. 🧠 Core Recursion Logic At every step: Choose a number i Reduce remaining sum Move start to i + 1 (avoid reuse) Mathematically, we search for: Where: 1 ≤ i1 < i2 < ... < ik ≤ 9 ⚡ Optimized Plan: ✅ Start from 1 ✅ If: cur.size() == k AND sum == 0 → valid combination ✅ If: cur.size() == k OR sum < 0 → prune ✅ Try numbers from start → 9 ✅ Backtrack properly ✅ Time Complexity: O(C(9, k)) (Bounded search space) ✅ Space Complexity: O(k) 💬 Challenge for you: 1️⃣ How can you add pruning to stop early when remaining numbers can't reach sum? 2️⃣ What if numbers were 1 to 20 instead of 1 to 9? 3️⃣ Can you solve this iteratively using bitmasking? #DSA #Day336 #LeetCode #Backtracking #Combinations #Recursion #Java #ProblemSolving #KeepCoding #100DaysOfCode
To view or add a comment, sign in
-
-
Day 12 – DSA Journey | Arrays 🚀 Today’s problem was about calculating trapped water using two pointers and boundary tracking. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • 🌧️ Trapping Rain Water 🔹 Trapping Rain Water 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 • ↔️ Used two pointers (left and right) • 📊 Maintained leftMax and rightMax values • 💧 Calculated trapped water based on the smaller boundary • 🔁 Moved pointers inward while updating maximum heights 𝐖𝐡𝐲 𝐓𝐡𝐢𝐬 𝐖𝐨𝐫𝐤𝐬 • 🧠 Water trapped depends on the minimum of leftMax and rightMax • 📌 Always process the smaller height side first • ⚡ Avoids using extra arrays for prefix/suffix max 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • 🎯 Two pointers can reduce space complexity • 📏 Boundary conditions matter more than the center • 🧠 Greedy movement decisions simplify complex problems • 🚀 Smart observation beats brute force 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 • ⏱ Time: O(n) • 📦 Space: O(1) 🧠 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Not every problem needs extra space — sometimes tracking the right boundaries is enough. On to Day 13 🔁🚀 #DSA #Arrays #TwoPointers #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
🔥 Day 342 – Daily DSA Challenge! 🔥 Problem: 🧍♂️ Queue Reconstruction by Height You are given an array people where each element is [h, k]: h → height of the person k → number of people in front who have height ≥ h Reconstruct and return the original queue. 💡 Key Insight — Greedy + Sorting The trick is to place taller people first. Why? Because shorter people won’t affect the k value of taller people. Sorting strategy: 1️⃣ Sort by height descending 2️⃣ If heights are equal → sort by k ascending This ensures we process the most restrictive constraints first. 🧠 Core Placement Logic After sorting, we insert each person at index k. Conceptually: Since taller people are already placed, inserting at position k guarantees exactly k taller/equal people in front. ⚡ Algorithm Steps ✅ Sort people by: height ↓ k ↑ ✅ Use a list to reconstruct queue ✅ For each person: insert at index k Queue building step-by-step produces the correct result. ⚙️ Complexity ✅ Time Complexity: O(n²) (list insertion cost) ✅ Space Complexity: O(n) 💬 Challenge for you: 1️⃣ Why must we process taller people first? 2️⃣ Can this be optimized using a Fenwick Tree or Segment Tree? 3️⃣ What happens if the constraint was shorter people instead of taller? #DSA #Day342 #LeetCode #Greedy #Sorting #Arrays #Java #ProblemSolving #KeepCoding #100DaysOfCode
To view or add a comment, sign in
-
-
Day 11 – DSA Journey | Arrays 🚀 Today’s problem was about solving something in O(n) time and O(1) space, which immediately removes most naive approaches. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • 🔎 First Missing Positive 🔹 First Missing Positive 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 • 🔄 Used the cyclic sort concept • 📌 Placed each number at its correct index (num → index num-1) • 🔁 Swapped elements until every valid number was positioned correctly • 🔍 Scanned the array to find the first index where nums[i] != i + 1 𝐖𝐡𝐲 𝐓𝐡𝐢𝐬 𝐖𝐨𝐫𝐤𝐬 • 📊 Only numbers in the range 1 to n matter • 🧠 Each number is placed in its “correct position.” • ⚡ Final scan reveals the smallest missing positive 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • 🎯 Constraints guide the approach • 🔁 Cyclic placement avoids extra space • 🧠 Index mapping is a powerful array trick • 🚀 In-place solutions often require thinking differently 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 • ⏱ Time: O(n) • 📦 Space: O(1) 🧠 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Sometimes the fastest solution isn’t about searching — It’s about placing things where they belong. On to Day 12 🔁🚀 #DSA #Arrays #CyclicSort #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
🚀 DSA Daily Challenge – Day 16: 3Sum (Medium) 🧠 Building on yesterday’s momentum, Day 16 is all about finding unique triplets that sum to zero — a perfect exercise for mastering two-pointer technique and duplicate handling. 🔍 Problem Recap Given an integer array nums, return all unique triplets [nums[i], nums[j], nums[k]] such that: nums[i] + nums[j] + nums[k] == 0 i != j != k No duplicate triplets 💡 Core Idea Instead of brute force O(n³), we optimize using: 1️⃣ Sort the array 2️⃣ Fix the first element i 3️⃣ Use two pointers j = i+1 and k = nums.length-1 If sum < 0 → move j forward If sum > 0 → move k backward If sum == 0 → store triplet and skip duplicates 4️⃣ Skip duplicates for i, j, and k 🧠 Why This Works Sorting lets us intelligently adjust pointers based on the current sum Duplicate skipping ensures unique triplets only Time Complexity: O(n²) Space Complexity: O(1) extra (ignoring output) 🧩 Dry Run Example Array: [-1, 0, 1, 2, -1, -4] After sorting: [-4, -1, -1, 0, 1, 2] Fix i = -1 → j = 2, k = 5 → sum = 0 → triplet [-1, -1, 2] Move pointers → triplet [-1, 0, 1] All duplicates skipped automatically, final result ✅ ⚡ Pattern Connection Two-pointer optimization Duplicate handling Builds foundation for: 3Sum Closest, 4Sum, and other sum-related array problems Reinforces mathematical transformation and efficient scanning techniques #DSA #LeetCode #Day16 #Java #TwoPointers #Arrays #CodingInterview #ProblemSolving #100DaysOfCode #DataStructures #InterviewPrep #Algorithm #MediumLevel #ProgrammingTips #CodingChallenge #Triplets #PrefixSum #RunningSum #EfficientSolutions #OptimizedCode
To view or add a comment, sign in
-
-
Today’s Problem of the Day was Trapping Rain Water — a classic but tricky problem that tests your understanding of two-pointer optimization. ✅ 1111 / 1111 test cases passed ✅ 1 / 1 attempt 🔥 4-day streak ⭐ 8/8 points Instead of using extra prefix/suffix arrays, I implemented the optimized O(n) time and O(1) space two-pointer approach. Key idea: At every index, trapped water depends on min(leftMax, rightMax) - height[i] The challenge isn’t writing code — it’s recognizing why the smaller boundary determines the water level. Problems like this reinforce: • Boundary thinking • Space optimization • Clean pointer movement logic Consistency > Motivation. On to Day 5. 💪 #GeeksforGeeks #ProblemOfTheDay #DataStructures #Algorithms #Java #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 DSA Challenge – Day 171 Problem: Exclusive Time of Functions ⏱️🔥 Today’s problem is a classic Stack simulation question that tests your understanding of function execution flow in a single-threaded CPU. 🧠 Problem Summary You are given: 👉 n functions with IDs from 0 to n-1 👉 A list of logs in the format: "{function_id}:{start|end}:{timestamp}" Rules: CPU is single-threaded Only one function runs at a time Functions can call other functions (nested / recursive) When a function starts → push to stack When it ends → pop from stack 🎯 Goal: Return an array where res[i] represents the exclusive time of function i. Exclusive time = actual execution time excluding time spent in child function calls. 💡 Key Insight This is a stack simulation problem. Why? Because: The most recently started function is always the one running. Nested calls pause the parent function. When a function ends: Duration = end_time - start_time + 1 Add duration to that function Subtract this duration from its parent (if exists) The +1 is important because: End timestamps are inclusive. ⚙️ Approach 1️⃣ Initialize: res = [0] * n stack = [] 2️⃣ For each log: Parse fid, type, time 3️⃣ If "start": Push (fid, time) onto stack 4️⃣ If "end": Pop from stack Compute duration Add to current function Subtract from parent (if stack not empty) 📈 Complexity Time Complexity: O(m) Where m = len(logs) Space Complexity: O(n) Stack depth in worst case. ✨ Why This Problem Is Important This teaches: ✅ Stack simulation ✅ Handling nested intervals ✅ Inclusive time calculation ✅ Managing parent-child execution overlap Very common in: System design interviews OS-related questions Execution trace problems Call stack simulation 🔖 #DSA #100DaysOfCode #Day171 #Stack #Simulation #LeetCode #Algorithms #InterviewPrep #CodingJourney #Python #ProblemSolving #SoftwareEngineering #TechCommunity
To view or add a comment, sign in
-
-
🔥 Day-7 — Container With Most Water (Two Pointer Pattern) 💻 Platform: LeetCode (#11) Before jumping into today’s problem, a quick note from yesterday: That problem strengthened my understanding of prefix–suffix contribution and space optimization. Coming to today’s challenge: Given an array of heights, choose two lines that hold the maximum water. The key formula: Area = min(height[left], height[right]) × width Instead of checking every pair (O(n²)), I used the Two Pointer technique: • Start with the widest container (left at 0, right at n-1) • Compute area • Move the pointer pointing to the smaller height • Continue shrinking the search space The most important realization: The shorter boundary limits the water level. Moving the taller boundary only reduces width without improving height — so it cannot produce a better result. 🔍 Key takeaways: ✔ Two Pointers is about eliminating impossible improvements ✔ Greedy pointer movement can lead to optimal solutions ✔ Starting from extremes can simplify search problems Learning to recognize patterns is making problem-solving feel less random each day. Solutions are available here: 🔗https://lnkd.in/gW8atfqw Day-7 complete. More tomorrow 🚀 #30DaysOfCode #LeetCode #DSA #Java #Algorithms #ProblemSolving #SoftwareEngineering #Developers
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development