The Logic of Symmetry Day 242 Today Today is day 242 of my coding journey and I am focusing on the Two Pointer technique. This is a very efficient way to solve problems on linear data structures like arrays and strings. The main idea is to use two different indices to move through the data from different ends or at different speeds. I practiced the Opposite Direction pattern today. In this pattern one pointer starts at index zero and the other at the end of the array. They move toward each other until they meet. This logic is perfect for comparison problems like checking if a string is a palindrome or reversing a string. Instead of using extra memory I can just swap or compare elements in place which makes the code much faster. I also worked on the Squares of a Sorted Array problem where I compared values from both ends to build a new sorted list. The Valid Word Abbreviation problem was a great challenge because I had to synchronize two pointers across a word and its abbreviation while handling numbers carefully. Learning these patterns helps me see the logic behind the code instead of just memorizing solutions. LeetCode questions I solved today: LeetCode 125 Valid Palindrome LeetCode 344 Reverse String LeetCode 977 Squares of a Sorted Array LeetCode 680 Valid Palindrome II LeetCode 408 Valid Word Abbreviation #DSAinJavaScript #365daysOfCoding #JavaScriptLogic #LeetCodeDaily #TwoPointers #ProblemSolving #AlgorithmPractice #LogicBuilding #CodingJourney #SoftwareDeveloper #WebDevelopment #DataStructures #JSAlgorithms #CleanCode #TechLearning #ProgrammingGoals #MERNStack #DailyCoding #FullStackDeveloper #CodingCommunity
Two Pointer Technique for Efficient Problem Solving
More Relevant Posts
-
Mastering Linear Logic Day 243 Today Today is day 243 of my coding journey, and I am continuing to refine my expertise in the Two Pointer technique. This strategy is a game-changer for linear data structures because it allows for efficient searching and comparison without the need for nested loops, keeping the time complexity at $O(n)$. Two Pointer Core Logic The core idea relies on using two indices to traverse an array or string from different positions. While it usually requires a sorted array, its power lies in three main patterns: Opposite Direction: Pointers start at each end and move toward the center (e.g., Palindrome checks). Same Direction: Fast and slow pointers help detect cycles or find middle elements. Sliding Window: Pointers track a range or subarray that expands and contracts based on constraints. Today's Solved Problems I focused on problems that involve comparison and searching pairs within sorted structures: LeetCode 125 Valid Palindrome: Used pointers at both ends to compare characters while ignoring non-alphanumeric symbols. LeetCode 344 Reverse String: Implemented an in-place swap using two pointers to achieve $O(1)$ space complexity. LeetCode 977 Squares of a Sorted Array: Leveraged the fact that the largest squares are at the ends of a sorted array containing negative numbers. LeetCode 167 Two Sum II: Since the array is already sorted, I used two pointers to narrow down the target sum in a single pass. LeetCode 408 Valid Word Abbreviation: A complex case where I synchronized pointers between a word and its compressed version, handling multi-digit jumps. Logic Tip: In the "3 Sum" problem, the strategy is to fix one pointer and then use the two-pointer technique on the remaining part of the array to find the missing pair. #DSAinJavaScript #365daysOfCoding #JavaScriptLogic #TwoPointers #LeetCodeDaily #ProblemSolving #Algorithms #DataStructures #CodingLife #LogicBuilding #CleanCode #JSDeveloper #WebDevelopment #ProgrammingJourney #SoftwareEngineering #TechLearning #MERNStack #DailyCoding #BackendLogic #CodingCommunity
To view or add a comment, sign in
-
🚀 Day 573 of #750DaysOfCode 🚀 🔍 Problem Solved: Maximize the Distance Between Points on a Square Today’s problem was 🔥 — a mix of geometry + greedy + binary search, and definitely one of those “think differently” questions. 💡 Key Insight: All points lie on the boundary of a square. 👉 Instead of treating this as 2D, we can convert it into a 1D problem by mapping each point to its position along the square’s perimeter. This simplifies the problem dramatically! 🧠 Approach: 1️⃣ Map 2D → 1D (Perimeter Mapping) Traverse square boundary in order Convert each point to a single number 2️⃣ Sort the mapped values 3️⃣ Binary Search on Answer Guess minimum distance d Check if we can pick k points such that each pair is ≥ d apart 4️⃣ Greedy Check Always pick next valid point using binary search Validate circular constraint (since square is a loop) 📈 Complexity: Time: O(n log n + log(side) × k log n) Space: O(n) ✨ Takeaway: 👉 Transform complex geometry into a linear problem 👉 Combine binary search on answer + greedy validation 👉 Think in terms of structure simplification This is the kind of problem that really sharpens problem-solving skills 💪 #LeetCode #DSA #Java #CodingJourney #ProblemSolving #BinarySearch #Algorithms #LearningEveryday #HardProblems
To view or add a comment, sign in
-
-
🚀 Day 28/50 – LeetCode Challenge 🧩 Problem: String Compression Today’s problem focused on modifying an array in-place while compressing repeated characters — a great exercise in two pointers and string manipulation. 📌 Problem Summary: Given an array of characters, compress it by replacing consecutive repeating characters with the character followed by its count. Example: Input: ["a","a","b","b","c","c","c"] Output: ["a","2","b","2","c","3"] The compression must be done in-place without using extra space. 🔍 Approach Used ✔ Used two pointers: one for reading characters one for writing compressed result ✔ Counted consecutive repeating characters ✔ Wrote the character and its count (if > 1) ✔ Continued until the end of the array ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) 💡 Key Learning ✔ In-place array manipulation ✔ Efficient use of two pointer technique ✔ Handling counts and conversions to string ✔ Writing optimized space-efficient solutions This problem highlights how careful pointer management can lead to efficient solutions. Consistency builds strong problem-solving skills 🚀 🔗 Problem Link: https://lnkd.in/geeBTB3P #50DaysOfLeetCode #LeetCode #DSA #TwoPointers #Strings #ProblemSolving #CodingJourney #FutureAIEngineer #Consistency
To view or add a comment, sign in
-
-
🚀 Day 82 of #100DaysOfCode Today, I solved LeetCode 41 – First Missing Positive, a classic hard problem that tests in-place array manipulation and optimization. 💡 Problem Overview: Given an unsorted array, the goal is to find the smallest missing positive integer in O(n) time and O(1) space. 🧠 Approach: ✔️ Used index-based placement (cyclic sort idea) ✔️ Placed each number x at index x - 1 whenever possible ✔️ Ignored negative numbers and values out of range ✔️ Finally, scanned the array to find the first index where the value is incorrect This ensures optimal time and space complexity without using extra data structures. ⚡ Key Takeaways: In-place manipulation can eliminate the need for extra space Index mapping is a powerful trick for array problems Hard problems often rely on simple but clever observations 📊 Complexity Analysis: Time Complexity: O(n) Space Complexity: O(1) Solving challenging problems and strengthening core fundamentals 🚀 #LeetCode #100DaysOfCode #DSA #Arrays #ProblemSolving #CodingJourney #SoftwareDevelopment #InterviewPrep #HardProblems
To view or add a comment, sign in
-
-
LeetCode Day 13 : Problem 42 (Trapping Rain Water) Just solved another LeetCode problem. It was "Trapping Rain Water", sounds like a physics problem, right? But here's what I actually learned: The core insight, for any position, the water it can hold is limited by the shorter of the two tallest walls surrounding it. min(maxLeft, maxRight) - height[i]. Once that clicked, the solution wrote itself. My first approach used two extra arrays, one for the tallest bar to the left of each position, one for the right. Three passes total. O(n) time, O(n) space. Clean and readable. Then I learned the O(1) space version using two pointers. Instead of pre-building arrays, move from both ends toward the middle. Whichever side is shorter determines the water level, process that side and move inward. Same result, no extra arrays. The pattern I keep seeing, when you need both left and right context, either do two passes and store results, or use two pointers and process on the fly. Same idea, different tradeoff between readability and space. Thirteen problems in. The two pass and two pointer patterns keep showing up in different forms. The more problems you solve, the more you recognise the shape of the solution before you write a single line. The real lesson? Understand why the brute force works first. The optimal solution is just the brute force with the extra space removed. #DSA #LeetCode #JavaScript #CodingJourney #Programming
To view or add a comment, sign in
-
-
My first “All Kill” in today’s LeetCode contest! 🚀 I gave the LeetCode Weekly Contest 498 and solve 4/4 questions. It was a relatively easier contest as most of the questions didn't test very high problem-solving or implementation skills, but were topic-based. If you are familiar with the underlying topics, you can solve these questions. I was lucky enough to be familiar with all these topics!! Here’s a brief breakdown of my approach: 1. Smallest Stable Index I (Easy) The constraints were small enough that brute force would work, but I noticed early that the 2nd question was the same as the first one and thus directly implemented an optimized approach in linear time. This way I could use the same code for the Q2. Just simply compute a prefix array for Max and suffix array for Min and get the first index that satisfies the conditions. We don't actually need a prefix array, the max can be calculated in the same loop as the loop to get the stable index, but to write the code faster i didn't think much and just implemented it with a prefix and suffix array. 2. Smallest Stable Index II (Medium) Same logic as Q1, just larger constraints, linear time solution works well. 3. Multi Source Flood Fill (Medium) Standard multi-source BFS. • Push all sources into the queue initially • Maintain a time matrix to track earliest arrival • If multiple colours reach a cell at the same time → choose the maximum colour 4. Count Good Integers on a Grid Path (Hard) A really interesting Digit DP + path simulation problem. Pretty standard. The only tricky part is to think of flattening the 2D grid • Convert each number into a 16-digit grid • Precompute the path positions from the directions • Apply digit DP with state tracking: • current index • last digit (to ensure non-decreasing sequence) • tight constraint • Count all valid numbers in range [l, r] Overall, a great contest and a confidence booster 💯 Now focusing on improving speed and handling tougher problems. #LeetCode #WeeklyContest #CompetitiveProgramming #DSA #ProblemSolving #LeetCodeContest #AllKill
To view or add a comment, sign in
-
-
🌞 Day 44 – LeetCode 75 ✅ 547. Number of Provinces Today’s problem was about finding how many connected components (provinces) exist in a graph represented using an adjacency matrix. Approach : I treated the matrix as a graph problem: - Each city = a node - isConnected[i][j] = 1 means there is a connection (edge) So the goal becomes: - Count how many disconnected groups exist. DFS Approach : - Maintain a visited[] array to track visited cities Loop through each city: - If not visited → it means a new province - Run DFS to mark all cities connected to it Complexity : - Time: O(n²) → because we scan adjacency matrix - Space: O(n) → visited array + recursion stack Key Insight : This is a classic Connected Components in Graph problem. Even though it looks like a matrix problem, it’s really: - How many disconnected graphs exist? Once you see that pattern, DFS/BFS becomes very natural. Restarting consistency again — building momentum one graph problem at a time 🚀 #LeetCode75 #Day44 #LeetCode #DSA #JavaScript #Graph #DFS #ConnectedComponents #ProblemSolving #Coding #LearningInPublic #Consistency
To view or add a comment, sign in
-
-
🚀 Day 79 of #100DaysOfCode Today, I solved LeetCode 32 – Longest Valid Parentheses, a challenging problem that focuses on stack-based logic and string processing. 💡 Problem Overview: Given a string containing only '(' and ')', the goal is to find the length of the longest valid (well-formed) parentheses substring. 🧠 Approach: ✔️ Used a stack-based approach to track indices ✔️ Initialized stack with -1 to handle edge cases ✔️ For every closing bracket, popped from stack ✔️ Calculated valid substring length using current index and stack top This approach efficiently tracks valid sequences and avoids reprocessing. ⚡ Key Takeaways: Stack is powerful for handling matching problems Index-based tracking simplifies substring calculations Handling edge cases (like invalid starting brackets) is crucial 📊 Complexity Analysis: Time Complexity: O(n) Space Complexity: O(n) Solving hard problems step by step and improving every day 🚀 #LeetCode #100DaysOfCode #DSA #Stack #Strings #ProblemSolving #CodingJourney #SoftwareDevelopment #InterviewPrep #HardProblems
To view or add a comment, sign in
-
-
Day 97/100 – #100DaysOfLeetCode 🚀 🧩 Problem: LeetCode 456 – 132 Pattern(Medium) 🧠 Approach: Traverse the array from right to left while maintaining a stack. Use a variable to track the “middle” element (the ‘2’ in 132 pattern) and check if a valid pattern exists. 💻 Solution: class Solution: def find132pattern(self, nums: List[int]) -> bool: stack = [] third = float('-inf') for i in range(len(nums) - 1, -1, -1): if nums[i] < third: return True while stack and nums[i] > stack[-1]: third = stack.pop() stack.append(nums[i]) return False ⏱ Time | Space: O(n) | O(n) 📌 Key Takeaway: Using a monotonic stack while iterating backwards helps efficiently detect complex patterns in linear time. #leetcode #dsa #development #problemSolving #CodingChallenge
To view or add a comment, sign in
-
Explore related topics
- LeetCode Array Problem Solving Techniques
- Leetcode Problem Solving Strategies
- Ways to Improve Coding Logic for Free
- Solving Sorted Array Coding Challenges
- Approaches to Array Problem Solving for Coding Interviews
- Simple Ways To Improve Code Quality
- Why Use Coding Platforms Like LeetCode for Job Prep
- Strategies for Writing Error-Free Code
- How to Refactor Code Thoroughly
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