🔥 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
Maximizing Container Water with Two Pointer Technique
More Relevant Posts
-
Day 81 - LeetCode Journey 🚀 Solved LeetCode 2: Add Two Numbers (Medium) — a classic linked list problem that beautifully combines arithmetic with pointer manipulation. At first, it looks like simple addition. But the twist is that numbers are stored in reverse order as linked lists, and we must simulate digit-by-digit addition. 💡 Core Idea (Simulation + Carry Handling): Traverse both linked lists simultaneously Add corresponding digits along with carry Create a new node for each digit of the result Move forward until both lists and carry are exhausted A dummy node helps in building the result list smoothly. 🤯 Why it works? Because we mimic the exact process of manual addition, handling carry at each step, ensuring correctness even when lengths differ. ⚡ Key Learning Points: • Converting real-world logic into code (digit addition) • Handling carry efficiently • Traversing two linked lists together • Using dummy node for clean construction • Managing different list lengths gracefully • Achieving O(max(n, m)) time and O(1) extra space This problem strengthens both logical thinking and linked list handling. Also, this pattern connects with: Add Binary Multiply Strings Linked List arithmetic problems Big integer calculations ✅ Better understanding of simulation problems ✅ Stronger pointer + arithmetic combination ✅ Improved handling of edge cases (carry, unequal lengths) From simple addition to linked list manipulation — this is where logic meets implementation 🚀 #LeetCode #DSA #Java #LinkedList #Algorithms #ProblemSolving #CodingJourney #Consistency #100DaysOfCode #InterviewPreparation #DeveloperGrowth #KeepCoding
To view or add a comment, sign in
-
-
🚀 Day 312 of solving 365 medium questions on LeetCode! 🔥 Today’s challenge: “622. Design Circular Queue” ✅ Problem: Design a circular queue (also called a "Ring Buffer"). It uses a fixed-size array and follows the FIFO (First In, First Out) principle, but connects the end of the array back to the front to reuse empty spaces left behind by dequeued elements! ✅ Approach (Array + Modulo Arithmetic) Instead of relying on built-in queue libraries, I implemented it from scratch using a fixed-size list and two running counters: Initialization: Create an array of size k and set absolute start and end counters to 0. Enqueue / Dequeue: Instead of manually resetting the pointers to 0 when they hit the end of the array, I just let them grow indefinitely! I used modulo arithmetic (index % k) to figure out exactly where that absolute counter maps to within the fixed circular array. Status Checks: isEmpty() is beautifully simple: start == end. isFull() is just: end == start + k. ✅ Key Insight The biggest headache when building a circular queue is distinguishing between a "Full" state and an "Empty" state, since traditional read/write pointers overlap in both scenarios. By letting the pointers act as absolute operation counters (and only applying modulo during array access), the capacity math becomes incredibly elegant. It completely eliminates the need for messy if/else wrap-around logic! ✅ Complexity Time: O(1) — Every single operation (enqueue, dequeue, front, rear, checks) executes in constant time. Space: O(K) — Where K is the predefined maximum capacity of the queue. 🔍 Python solution attached! 🔥 Flexing my coding skills until recruiters notice! #LeetCode365 #DataStructures #Queue #Python #ProblemSolving #DSA #Coding #SoftwareEngineering
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
-
-
🚀 Day 14 of My DSA Journey Today I solved LeetCode 11 – Container With Most Water on . 📌 Problem You are given an array "height" where each element represents the height of a vertical line. The goal is to find two lines that together with the x-axis form a container that can hold the maximum amount of water. Example: Input: "[1,8,6,2,5,4,8,3,7]" Output: "49" --- 🧠 Approach – Two Pointer Technique A brute force solution would check all possible pairs, which takes "O(n²)" time. Instead, I used the Two Pointer approach to optimize the solution. Steps I followed: • Initialize two pointers: - "p1" at the start of the array - "p2" at the end of the array • Calculate the water trapped between them using: Area = "min(height[p1], height[p2]) × (p2 - p1)" • Keep track of the maximum area found so far. • Move the pointer pointing to the smaller height, because moving the larger one will not increase the area. • Continue until the pointers meet. This strategy efficiently reduces the search space while ensuring we explore all optimal possibilities. --- ⏱ Time Complexity: "O(n)" 📦 Space Complexity: "O(1)" --- 💡 Key Learnings ✔ Applying the Two Pointer technique for optimization ✔ Understanding how to reduce brute-force complexity from O(n²) to O(n) ✔ Recognizing patterns in array-based problems Another day of consistent learning and problem-solving 🚀 #100DaysOfCode #DSA #TwoPointers #LeetCode #Java #ProblemSolving #CodingJourney #Consistency
To view or add a comment, sign in
-
-
Day 63/100 – #100DaysOfLeetCode 🚀 🧩 Problem: LeetCode 167 – Two Sum II - Input Array Is Sorted (Medium) 🧠 Approach: Use two pointers from both ends. Move left or right based on whether the sum is smaller or larger than the target. 💻 Solution: class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: left = 0 right = len(numbers) - 1 while left < right: current_sum = numbers[left] + numbers[right] if current_sum == target: return [left + 1, right + 1] elif current_sum < target: left += 1 else: right -= 1 ⏱ Time | Space: O(n) | O(1) 📌 Key Takeaway: Two-pointer technique is highly efficient for sorted array problems, reducing time complexity without extra space. #leetcode #dsa #development #problemSolving #CodingChallenge
To view or add a comment, sign in
-
-
🔥 Day-9 — Rotate Array (Array Manipulation + Reversal Trick) 🧩 Problem: Rotate Array 💻 Platform: LeetCode (#189) Given an array, rotate it to the right by k steps. At first, this looks like a simple shifting problem. Brute force idea: Shift elements one by one, k times. Time Complexity → O(n × k). Not scalable. Better idea: Use an extra array and place elements at correct rotated positions. Time → O(n) Space → O(n) But the optimal solution? 🚀 Reverse Technique (In-Place) Steps: 1️⃣ Reverse the entire array 2️⃣ Reverse first k elements 3️⃣ Reverse remaining n − k elements That’s it. Time Complexity: O(n) Space Complexity: O(1) 💡 Why this works: Reversal repositions elements into their final rotated order without needing extra memory. It’s not obvious at first — but once you visualize it, it becomes clean and elegant. Key Takeaways: ✔ Not all array problems require extra space ✔ In-place manipulation is a powerful skill ✔ Sometimes the trick is not shifting — but reordering cleverly Each day I’m realizing: Patterns repeat. Tricks repeat. Only the surface changes. Day-9 complete. Onward 🚀 #30DaysOfCode #LeetCode #DSA #Java #Arrays #Algorithms #ProblemSolving #SoftwareEngineering #Developers
To view or add a comment, sign in
-
-
#100DaysOfCode 🚀 👉Solved: LeetCode 75 – Sort Colors The goal was to sort an array containing only three values: 0 (Red), 1 (White), and 2 (Blue) At first glance this looks like a simple sorting problem. But the twist: ❌ No built-in sort ✔ One pass ✔ Constant space The solution uses the famous **Dutch National Flag Algorithm**. Instead of sorting normally, we maintain three pointers: • low → for 0s • mid → current element • high → for 2s Rules: • If nums[mid] == 0 → swap with low • If nums[mid] == 1 → move mid forward • If nums[mid] == 2 → swap with high This allows sorting the array in a single pass. 📌 Key Points: ✔ In-place sorting ✔ One pass algorithm ✔ Constant space usage ✔ Classic three-pointer technique ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) Problems like this show how powerful pointer techniques can be. Day 15✅ #DSA #Java #LeetCode #Algorithms #ProblemSolving #100DaysOfCode #CodingJourney #LearnInPublic
To view or add a comment, sign in
-
-
Here's what I learned solving LeetCode 153 — Find Minimum in Rotated Sorted Array 🔄 At first glance it looks simple: just find the smallest number. But the O(log n) requirement means you can't just scan the array — you have to use binary search. The insight that clicked for me: In a rotated sorted array, the minimum is always at the inflection point — where the big numbers end and the small numbers begin. You can find it with one rule: → At each midpoint, compare nums[mid] to nums[right] • If mid > right, the rotation is in the right half → search right • If mid ≤ right, the minimum is at mid or to its left → search left That single comparison is all you need. No edge case chaos. No extra flags. The bigger lesson? Binary search isn't just for finding a target value. Anytime you can look at the midpoint and definitively eliminate half the array, binary search applies. It's a pattern worth internalizing — it shows up everywhere. #LeetCode #DSA #CodingInterview #BinarySearch #SoftwareEngineering [My Solution](https://lnkd.in/eDQ32XQm)
To view or add a comment, sign in
-
Day 49 – DSA Journey 🚀 | Revisiting a Classic Merge Problem Continuing my daily DSA practice, today I revisited a classic array problem on LeetCode to strengthen my understanding of pointer-based logic. 📌 Problem Practiced: Merge Sorted Array (LeetCode 88) 🔍 Problem Idea: We are given two sorted arrays where the first array has extra space at the end to hold elements from the second array. The task is to merge both arrays into a single sorted array inside the first array. 💡 Key Insight: Instead of merging from the start (which may overwrite elements), we can start from the end and place the larger element first using pointers. 📌 Approach Used: • Use three pointers for the last valid elements of both arrays and the final position • Compare elements from the end of both arrays • Place the larger element at the last position of the first array • Move pointers until all elements are merged 📌 Concepts Strengthened: • Two-pointer technique • In-place array manipulation • Merge logic used in Merge Sort • Careful pointer movement ⏱️ Time Complexity: O(m + n) 📦 Space Complexity: O(1) Today’s takeaway: Revisiting problems helps reinforce core concepts and improves clarity in implementation. On to Day 50! 🚀 #Day49 #DSAJourney #LeetCode #Arrays #TwoPointers #Java #ProblemSolving #LearningInPublic #Consistency
To view or add a comment, sign in
-
-
Sometimes a brute force approach is more than enough before jumping to complex optimizations. 🚀 While solving LeetCode 3713 – Longest Balanced Substring, I followed a straightforward brute-force strategy that worked effectively within constraints. 🔍 Approach: The idea is to check every possible substring and verify whether it is balanced. A substring is considered balanced if all characters present in it appear the same number of times. 1. Iterate through every possible starting index i. 2. For each start, extend the substring with index j. 3. Maintain a frequency array of size 26 to track occurrences of characters. 4. After each extension, check whether all non-zero frequencies are equal. 5. If the substring is balanced, update the maximum length. (The helper function verifies the balance condition by ensuring all characters that appear in the substring have the same frequency.) ⏱ Time Complexity: >Outer loop for start index → O(n) >Inner loop for end index → O(n) >Balance check over 26 characters → O(26) ≈ O(1) >Overall Time Complexity: O(n²) 💾 Space Complexity: >Frequency array of size 26 → O(1) (constant space) ✨ Sometimes the simplest idea—checking all possibilities carefully—can solve the problem efficiently without overcomplicating the solution. #LeetCode #ProblemSolving #DataStructures #Algorithms #Java #CodingJourney
To view or add a comment, sign in
-
Explore related topics
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