🚀 Day 7: Cracking the "Two Pointer" Pattern 🚀 Today, I dived into LeetCode 167 (Two Sum II) to master the Two Pointer technique! While the standard Two Sum problem is often solved with a Hash Map, a Sorted Array gives us a secret advantage. By using two pointers—one at the start and one at the end—we can find the target sum in $O(n)$ time and $O(1)$ space. No extra memory needed! 🧠 💡 Key Takeaway: The magic happens in the movement: Sum < Target? Move the left pointer to grab a larger value. Sum > Target? Move the right pointer to grab a smaller value. Pro Tip: Always watch out for 1-indexed requirements! Adding that +1 to your return indices is the difference between a "Wrong Answer" and "Accepted." ✅ 🛠️ The Logic (Java): Java while (left < right) { int sum = numbers[left] + numbers[right]; if (sum == target) return new int[]{left + 1, right + 1}; else if (sum < target) left++; else right--; } One week down, more patterns to go! Following the roadmap from the "25 DSA Patterns" series. 📈 #DSA #LeetCode #CodingChallenge #Java #TwoPointers #SoftwareEngineering #Consistency
Mastering Two Pointer Technique on LeetCode
More Relevant Posts
-
Day 58/100 | #100DaysOfDSA 🔄🔍 Today’s problem: Search in Rotated Sorted Array A twist on Binary Search with a rotated array. Key idea: Even though the array is rotated, one half is always sorted. Approach: • Use binary search • Find mid element • Check which half is sorted (left or right) • Decide if target lies in the sorted half • Narrow the search accordingly Why it works: At every step, we eliminate half of the search space just like standard binary search. Time Complexity: O(log n) Space Complexity: O(1) Big takeaway: Understanding the structure of the problem helps adapt classic algorithms like binary search. Rotation doesn’t break order — it just shifts it. 🔥 Day 58 done. #100DaysOfCode #LeetCode #DSA #Algorithms #BinarySearch #Arrays #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity
To view or add a comment, sign in
-
-
#100DaysOfCode – Day 2 Today I worked on a DSA problem based on arrays: Check if an array is sorted and rotated 🔍 Approach: Instead of finding the exact rotation point, I focused on identifying a pattern: In a sorted and rotated array, the order should break at most once. So, I checked how many times an element is greater than the next element while traversing the array in a circular manner. ✔️ If the count of such breaks is 0 or 1 → valid ❌ If it’s more than 1 → not a sorted rotated array 🧠 Key Takeaway: This problem taught me how pattern observation can simplify logic and avoid unnecessary complexity. Sometimes the best solution is not the most obvious one! 📈 Staying consistent and improving step by step 💪 #100DaysOfCode #DSA #DataStructures #Algorithms #Java #CodingJourney #ProblemSolving #LeetCode #Consistency
To view or add a comment, sign in
-
-
Day 9/ #100DaysOfCode Solved LeetCode 1848: Minimum Distance to the Target Element. Approach: The problem can be solved using a straightforward linear traversal. Iterate through the array and check for indices where the value equals the target. For each such index, compute the absolute difference between the current index and the given start index. Maintain a variable to track the minimum distance encountered during the traversal. Solution Insight: Initialize a variable with a large value (e.g., Integer.MAX_VALUE). Traverse the array once. Whenever the target element is found, update the minimum distance using Math.abs(i - start). Return the minimum value after the loop. Complexity: Time Complexity: O(n) Space Complexity: O(1) Result: 72/72 test cases passed with optimal runtime performance. This problem reinforces the importance of simple iteration and careful tracking of minimum values in array-based problems. #100DaysOfCode #LeetCode #DSA #Java #ProblemSolving #Algorithms
To view or add a comment, sign in
-
-
🚀 Solved: Find Dominant Index (LeetCode) Just solved an interesting problem where the goal is to find whether the largest element in the array is at least twice as large as every other number. 💡 Approach: 1. First, traverse the array to find the maximum element and its index. 2. Then, iterate again to check if the max element is at least twice every other element. 3. If the condition fails for any element → return "-1". 4. Otherwise → return the index of the max element. 🧠 Key Insight: Instead of comparing all pairs, just track the maximum and validate it — keeps the solution clean and efficient. ⚡ Time Complexity: O(n) ⚡ Space Complexity: O(1) 💻 Code (Java): class Solution { public int dominantIndex(int[] nums) { int max = -1; int index = -1; // Step 1: find max and index for (int i = 0; i < nums.length; i++) { if (nums[i] > max) { max = nums[i]; index = i; } } // Step 2: check condition for (int i = 0; i < nums.length; i++) { if (i == index) continue; if (max < 2 * nums[i]) { return -1; } } return index; } } 🔥 Got 100% runtime and 99%+ memory efficiency! #LeetCode #DSA #Java #Coding #ProblemSolving #Algorithms
To view or add a comment, sign in
-
-
Day 71/100 Completed ✅ 🚀 Solved LeetCode – Reshape the Matrix (Java) ⚡ Implemented an efficient matrix transformation approach by mapping elements from the original matrix to the reshaped matrix using a single traversal. Instead of creating intermediate structures, used index manipulation (count / c, count % c) to place elements correctly while maintaining row-wise order. 🧠 Key Learnings: • Understanding how to map 2D indices into a linear traversal • Efficiently converting between different matrix dimensions • Handling edge cases where reshape is not possible • Writing clean and optimized nested loop logic 💯 This problem strengthened my understanding of matrix traversal and index mapping techniques, which are very useful in array and grid-based problems. 🔗 Profile: https://lnkd.in/gaJmKdrA #leetcode #datastructures #algorithms #java #matrix #arrays #problemSolving #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
DSA Day 11 – Prefix Sum + HashMap Pattern Today I solved the “Subarray Sum Equals K” problem on LeetCode. Problem: Given an array and an integer k, find the total number of subarrays whose sum equals k. Approach Used: -> Used Prefix Sum to keep track of cumulative sum -> Used HashMap to store frequency of prefix sums -> At each step, checked if (currentSum - k) exists in map -> If yes → added its frequency to count Time Complexity: -> O(n) Space Complexity: -> O(n) Key Learning: -> Prefix Sum helps convert subarray problems into simple calculations -> HashMap allows constant time lookup for previous sums -> Instead of checking all subarrays (O(n²)), we optimize to O(n) What I Realized: Earlier I used brute force for subarrays, but today I understood how prefix sum + hashmap eliminates nested loops completely. This pattern is powerful for many subarray problems. Thanks to Pulkit Aggarwal sir for guiding me in DSA and helping me understand problem-solving patterns. Consistency is turning into real problem-solving ability. #DSA #LeetCode #Java #ProblemSolving #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
Day 76/100 Completed ✅ 🚀 Solved LeetCode – Search a 2D Matrix (Java) ⚡ Implemented an optimized binary search approach by treating the 2D matrix as a flattened sorted array. Converted 1D index into 2D coordinates (row = mid / m, col = mid % m) to efficiently locate the target in O(log(m × n)) time. 🧠 Key Learnings: • Applying binary search on a 2D matrix • Converting 1D index to 2D (row & column mapping) • Reducing time complexity from O(m × n) → O(log(m × n)) • Importance of problem observation (matrix behaves like sorted array) 💯 This problem strengthened my understanding of binary search variations and how to apply it beyond simple 1D arrays. 🔗 Profile: https://lnkd.in/gaJmKdrA #leetcode #datastructures #algorithms #java #matrix #binarysearch #arrays #optimization #problemSolving #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
**Day 116 of #365DaysOfLeetCode Challenge** Today’s problem: **Next Greater Element II (LeetCode 503)** A classic **Monotonic Stack** problem with a twist: 👉 The array is **circular** So after the last element, we continue from the first element. 💡 **Core Idea:** For every number, find the **first greater element** while traversing forward. If none exists → return `-1` Example: Input: `[1,2,1]` Output: `[2,-1,2]` Why? * First `1 → 2` * `2 → no greater` * Last `1 → wrap around → 2` 📌 **Efficient Approach: Monotonic Stack** Use stack to store indices whose next greater element is not found yet. Traverse array **twice**: `0 → 2*n - 1` Use: `idx = i % n` This simulates circular behavior. Whenever current number is greater than stack top element: 👉 Pop index 👉 Update answer ⚡ **Time Complexity:** O(n) ⚡ **Space Complexity:** O(n) **What I learned today:** Circular array problems often become simple when you traverse twice using modulo. 👉 `i % n` This trick appears in many advanced array questions. 💭 **Key Takeaway:** When you see: * Next Greater Element * Previous Smaller Element * Nearest Bigger Value #LeetCode #DSA #MonotonicStack #Stack #Arrays #Java #CodingChallenge #ProblemSolving #TechJourney #Consistency
To view or add a comment, sign in
-
-
🚀 Day 3/100 – LeetCode Challenge 🔍 Problem: Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be inserted to maintain the sorted order. 💡 Key Concepts Used: • Binary Search • Time Complexity Optimization – O(log n) • Efficient searching in sorted arrays 📚 What I Learned: • How binary search reduces search time significantly compared to linear search • Handling edge cases when the target element is not present • Determining the correct insertion index while maintaining sorted order hashtag #100DaysOfCode #LeetCode #Java #DataStructures #Algorithms #BinarySearch #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
Day 57/100 | #100DaysOfDSA ⛰️🔍 Today’s problem: Peak Index in a Mountain Array A perfect use-case of Binary Search on a pattern. Key observation: The array increases → reaches a peak → then decreases. Approach: • Use binary search on the index • Compare mid with mid + 1 • If arr[mid] > arr[mid + 1] → we are on the decreasing side → move left • Else → we are on the increasing side → move right This guarantees we always move toward the peak. Time Complexity: O(log n) Space Complexity: O(1) Big takeaway: Binary search isn’t just for sorted arrays — it works on patterns too. Recognizing these patterns is a game changer. 🔥 Day 57 done. #100DaysOfCode #LeetCode #DSA #Algorithms #BinarySearch #Arrays #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity
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