🚀 𝗡𝗲𝘄 𝗣𝗥 𝗠𝗲𝗿𝗴𝗲𝗱 I recently tackled a fun logical puzzle: how to move all zeroes to the end of an array while maintaining the relative order of the non-zero elements. This challenge, which I've documented in my latest PR (https://lnkd.in/dSXWnSES), really tested my ⚙️ 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 to array manipulation. My solution involved iterating through the array and using a pointer to keep track of the position where the next non-zero element should be placed. This allowed me to effectively "compress" the non-zero elements to the front, implicitly leaving zeroes at the end. During the process, I leaned on dry runs to trace the array's state and visualize the pointer movements. When I hit a snag, the debugger was invaluable for stepping through the logic line by line and understanding exactly where my assumptions were off. A key takeaway for me was the power of in-place modification and how a well-placed pointer can simplify array problems significantly. How do you ⚙️ 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 similar array manipulation challenges? Share your strategies below! 📦 Repo: https://lnkd.in/dSXWnSES #ArrayManipulation #JavaScript #Algorithms #ProblemSolving #CodingChallenge #DataStructures #InPlaceAlgorithms #LogicalReasoning #SoftwareDevelopment #LeetCodeStyle
Moving Zeroes to End in Array with In-Place Approach
More Relevant Posts
-
Stop Shifting Elements. Use Two Pointers Instead ⚡📦 Solved LeetCode 283 (Move Zeroes) today. Problem 🔍 Move all 0s to the end while maintaining the order of non-zero elements. Initial thought 🧠 Shift elements or use extra array. Works, but increases time or space complexity. Better approach 🚀 Use two pointers: 1️⃣ One pointer tracks position for next non-zero 2️⃣ Traverse array 3️⃣ Swap non-zero elements forward Mental model 🧩 Partition the array: Left → non-zero zone Right → zero zone Interview takeaway 🎯 When rearranging elements in-place while preserving order, think two pointers + partitioning. Practical insight 💡 Avoid unnecessary swaps. Only move when needed to keep operations minimal. Time: O(n) Space: O(1) #DSA #LeetCode #Algorithms #TwoPointers #JavaScript #CodingInterview #InterviewPrep #ArrayProblems
To view or add a comment, sign in
-
The Efficiency of the Sliding Window 🪟🏃 Consistency isn't just about writing code; it's about refining the logic until the "edge cases" no longer feel like obstacles. Today was all about moving from brute-force thinking to an optimized Sliding Window approach. 1️⃣ What I Studied & Solved I focused on the Fixed-Size Sliding Window pattern. The Problem: Finding the Maximum Sum Subarray of size k in an array of integers. The Challenge: Moving away from a nested loop approach — O(n²) — which re-calculates the sum for every possible sub-section, and instead using a linear scan — O(n). 2️⃣ Key Takeaways The Entry/Exit Strategy: Instead of re-summing k elements every time the window moves, I implemented the "O(1) update." You simply add the new element entering the window and subtract the one leaving it. Overcoming the "Off-by-One" Error: I initially struggled with missing the first and last windows. I refined my logic to ensure the maxSum is checked after the window reaches full capacity but before the trailing element is removed. Pointer Coordination: Using two pointers (p1 and p2) to represent the boundaries of the window made the "sliding" logic much more visual and easier to debug. 3️⃣ Time & Space Complexity Time Complexity: O(n) Since we only traverse the array once and perform constant-time additions/subtractions at each step, the algorithm is incredibly efficient even for massive datasets. Space Complexity: O(1) We only store a few variables (currentSum, maxSum, and the pointers) regardless of how large the input array grows. 4️⃣ Conclusion Debugging my own "off-by-one" errors today taught me more than a perfect first-time solution ever could. Engineering is about handling those boundaries. One more pattern mastered, and the "mental muscle" for problem-solving is definitely getting stronger. 💪 #JavaScript #DSA #SlidingWindow #CodingJourney #WebDevelopment #SoftwareEngineering #Consistency #ProblemSolving
To view or add a comment, sign in
-
-
Day 17 of #LeetCodeDaily Problem: Sort Colors (Medium) Given an array with values 0, 1, 2 representing colors (Red, White, Blue), sort them in-place without using any built-in sort. 🔍 My Approach: Use Dutch National Flag Algorithm (3-pointer approach) Maintain three pointers: low → position for 0 mid → current element high → position for 2 Algorithm: If element is 0 → swap with low, move both low & mid If element is 1 → just move mid If element is 2 → swap with high, move high only This ensures: Left side → all 0s Middle → all 1s Right side → all 2s ⏱ Time: O(n) 📦 Space: O(1) Single pass + in-place sorting makes it optimal 🚀 💡 Learning: When array has limited values → think partitioning Key insight → don’t move mid when swapping with high Always re-check swapped elements Classic problem to test pointer manipulation skills #ProblemSolving #LeetCode #JavaScript #DSA #Algorithms #Array #InterviewPrep #CodingJourney #30DaysDSAChallenge #LearningInPublic
To view or add a comment, sign in
-
-
🚀 Just Uploaded a New LeetCode Solution! Solved LeetCode #26 – Remove Duplicates from Sorted Array using the Two Pointer Technique in JavaScript. This is a must-know pattern for coding interviews — simple idea, but very powerful when applied correctly. 👉 In this video, I’ve covered: Intuition behind the problem Step-by-step dry run Optimal in-place solution (O(n) time, O(1) space) Clean and easy-to-understand JavaScript code 🔗 Watch here: https://lnkd.in/g-HgkGXQ If you're preparing for coding interviews or strengthening your DSA fundamentals, this one is definitely worth your time. Would love to hear your approach to this problem — drop it in the comments 👇 #leetcode #dsa #codinginterview #javascript #twopointer #programming #softwaredevelopment #coding #developers #learning #jdcodebase
Remove Duplicates from Sorted Array | Optimal Two Pointer Approach 🔥 | LeetCode Explained (JS)
https://www.youtube.com/
To view or add a comment, sign in
-
Solved Leetcode 497 - Next Greater Element I Here’s the key insight: Use a monotonic decreasing stack. Traverse from right to left. For each element, remove all smaller elements from the stack. The top of the stack becomes the next greater element. To make it efficient for queries, store the results in a map: number → next greater element This reduces the complexity from O(n²) to O(n). What clicked for me was this: The stack is used for computation, and the map is used for fast retrieval. Once you understand this separation of roles, a whole category of problems becomes easier: Next Greater Element Previous Greater Element Stock Span Daily Temperatures #DataStructures #Algorithms #JavaScript #CodingInterview #LeetCode #ProblemSolving
To view or add a comment, sign in
-
-
💡 Understanding Two Sum — It’s Not About the Numbers, It’s About Timing Today I revisited the classic Two Sum problem and realized something simple but powerful: 👉 The algorithm doesn’t try to find the best pair 👉 It doesn’t look for largest numbers 👉 It doesn’t check all possibilities It simply returns the first valid pair it encounters during traversal Key Insight: The result depends entirely on the order of iteration Example: nums = [1, 2, 4, 5, 6, 8] target = 10 We might expect: 2 + 8 = 10 → indices [1, 5] But the algorithm returns: 4 + 6 = 10 → indices [2, 4] Why? Because: 4 is seen earlier 6 appears soon after The algorithm stops immediately when it finds the first match The Rule to Remember: 🧠 Hash map solution returns the first valid pair based on traversal order Takeaway: This isn’t just about solving Two Sum — it’s about understanding how algorithm behavior is shaped by execution flow, not just logic. Once you see this, you stop memorizing solutions and start actually understanding them. #JavaScript #Algorithms #CodingInterview #SoftwareEngineering #ProblemSolving
To view or add a comment, sign in
-
-
🚀 𝗡𝗲𝘄 𝗣𝗥 𝗠𝗲𝗿𝗴𝗲𝗱 I recently tackled the challenge of reversing an array in-place. The core 🧩 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 was to modify the original array directly without creating a new one, which requires careful index management. To solve this, I implemented the two-pointer technique in JavaScript. I used one pointer starting at the beginning of the array and another at the end. I then swapped the elements pointed to by these pointers and moved them towards the center until they met or crossed. This ⚙️ 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 ensures O(1) space complexity. My 🐞 𝗗𝗲𝗯𝘂𝗴𝗴𝗶𝗻𝗴 𝗣𝗿𝗼𝗰𝗲𝘀𝘀 involved dry runs to trace the pointer movements and element swaps. Visualizing the array's state at each step was crucial. I also occasionally used the debugger to step through the code and confirm my understanding of the logic. A 📚 𝗞𝗲𝘆 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴 from this exercise was the power of in-place algorithms for optimizing memory usage, especially when dealing with large datasets. You can see the implementation in my latest PR: https://lnkd.in/d5rAw_CN What are your favorite in-place algorithms or techniques? 📦 Repo: https://lnkd.in/d5rAw_CN #DataStructures #Algorithms #JavaScript #TwoPointerTechnique #ProblemSolving #InPlaceAlgorithm #CodingChallenge #SoftwareDevelopment #ArrayManipulation
To view or add a comment, sign in
-
-
From a for loop to two pointers — here's how I leveled up on the Is Subsequence problem. When I first saw this problem, my brain went straight to the obvious: Loop through string s, and for each character, check if it exists somewhere in string t. If all characters are found — it's a subsequence. Simple. Done. But then I asked myself — can we do better? --- 🔍 The Brute Force Thinking The initial approach feels natural: - Iterate over s - For each character, scan t to find a match - If all match → return true It works. But it's not the cleanest, and it doesn't respect the ORDER constraint fully in an intuitive way. --- ⚡ The Two Pointer Breakthrough Then came the aha moment — two pointers. - i points to s, j points to t - Run a single loop through t - If s[i] === t[j], move i forward (we matched a character!) - Always move j forward - At the end — if i === s.length, every character in s was found in order inside t function isSubsequence(s, t) { let i = 0, j = 0; while (j < t.length) { if (s[i] === t[j]) i++; j++; } return i === s.length; } One pass. No nested loops. Clean and elegant. --- 💡 The Real Lesson The brute force got me to the answer. But thinking about TWO pointers taught me to think about the problem differently — not just "does the character exist" but "are we moving forward together through both strings?" #DSA #CodingJourney #TwoPointers #JavaScript #ProblemSolving #LeetCode #SoftwareDevelopment
To view or add a comment, sign in
-
Solved “Add Two Numbers” on LeetCode with an efficient approach using linked list traversal and carry handling. Key highlights: Used a dummy node to simplify list construction Handled different list lengths seamlessly Managed carry propagation correctly across nodes Achieved optimal time complexity O(max(n, m)) Performance: Runtime: 3 ms (faster than ~55%) Memory: 61.25 MB (better than ~79%) This problem reinforces how mastering fundamentals like linked lists and pointer manipulation is crucial for writing clean and scalable solutions. Consistent practice is the real edge. #leetcode #datastructures #algorithms #coding #javascript #problemSolving #softwareengineering
To view or add a comment, sign in
-
-
When Prefix Sums Repeat, Something Interesting Happens 🔁📊 Solved LeetCode 523 today. Problem 🔍 Check if a subarray of length ≥ 2 exists whose sum is divisible by k. Initial thought 🧠 Check every subarray using prefix sums. But that quickly becomes O(n²). Better approach 🚀 Use Prefix Sum + Remainder HashMap. Store the first index where each remainder appears. If the same remainder appears again and currentIndex - previousIndex >= 2, a valid subarray exists. Mental model 🧩 If: prefix[j] % k = prefix[i] % k Then: prefix[j] - prefix[i] is divisible by k. Interview takeaway 🎯 Subarray + divisibility → Prefix Sum + Remainder tracking. Practical insight 💡 Store the first occurrence of each remainder to maximize subarray length detection. This same pattern appears in problems like 974 and 560. #DSA #LeetCode #Algorithms #PrefixSum #HashMap #JavaScript #CodingInterview #InterviewPrep
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