Move Zeroes — Two Pointer O(n) In-Place Solution [Meta Interview]
Move all zeroes to end while maintaining relative order of non-zero elements. Optimal O(n) two-pointer solution with minimal writes. Full C, C++, Java, JavaScript and Python code.
webcoderspeed.com
85 articles
Move all zeroes to end while maintaining relative order of non-zero elements. Optimal O(n) two-pointer solution with minimal writes. Full C, C++, Java, JavaScript and Python code.
Merge two sorted arrays in-place by filling from the end. The classic 3-pointer technique asked at Meta and Microsoft. Full solutions in C, C++, Java, JavaScript and Python.
Remove duplicates from a sorted array in-place using the write pointer pattern. O(n) time, O(1) space. Full solutions in C, C++, Java, JavaScript, Python with follow-up for allowing k duplicates.
Reverse a character array in-place using two pointers. O(n) time, O(1) space. The fundamental two-pointer swap pattern.
Determine if a string is a palindrome considering only alphanumeric characters and ignoring cases. Two pointer O(n) O(1) solution with all 5 language implementations.
Find all unique triplets summing to zero. Sort array then fix one element and use two pointers. Full O(n²) solution in C, C++, Java, JavaScript and Python.
Find two lines that together with the x-axis form a container holding the most water. Greedy two-pointer O(n) — never check a pair that can't be optimal.
Rotate array right by k steps. Triple reverse trick: reverse whole, reverse first k, reverse rest. O(n) time O(1) space.
Find the lexicographically next permutation in-place using a two-pass scan from the right.
Sort an array of 0s, 1s, and 2s in-place in one pass using Dijkstra's Dutch National Flag algorithm.
Find the smallest contiguous subarray with sum >= target using the shrinkable sliding window technique.
Find all unique quadruplets summing to target by extending the 3Sum pattern with an outer loop and duplicate skipping.
Calculate trapped rain water using inward two pointers that track left-max and right-max, replacing the classic O(n) space approach.
Count subarrays where max element is in [L,R] using a clever counting formula with two linear scans.
Calculate water trapped between bars. Two-pointer approach: maintain max_left and max_right; water at each position = min(max_left, max_right) - height.
Find the intersection node of two linked lists in O(n) O(1) by switching pointers at the end of each list.
Remove all nodes that have duplicate numbers from a sorted linked list using a dummy head and skip logic.
Swap the kth node from the front with the kth node from the end by finding both with two pointers.
Compare two strings after applying backspace characters in O(1) space by scanning from right with skip counters.
Master Two Pointers and Sliding Window patterns with 60 problems, 5-language solutions, and MAANG company tags.
Check if a string is a palindrome after removing non-alphanumeric characters using inward two pointers.
Reverse an array of characters in-place using the classic two-pointer swap technique.
Return squares of a sorted array in sorted order using two pointers that compare absolute values from both ends.
Remove all occurrences of val in-place using a write pointer pattern, returning the new length.
Remove duplicates in-place from a sorted array using a write pointer that only advances on unique elements.
Merge two sorted arrays in-place from the end to avoid overwriting elements using three pointers.
Check if string s is a subsequence of t using a greedy two-pointer scan that matches characters in order.
Find the maximum number of consecutive 1s achievable by flipping at most k zeros, using a variable sliding window.
Count days with fixed-size window sums above upper and below lower thresholds using a sliding fixed window.
Compute the running sum of a 1D array where each element is the sum of itself and all previous elements.
Find the longest substring without duplicate characters using a HashSet-backed shrinkable sliding window.
Find the longest substring with at most k character replacements by tracking the maximum frequency char in the window.
Check if any permutation of s1 is a substring of s2 using a fixed-size sliding window with character frequency comparison.
Find the maximum fruits you can collect starting from any tree with two baskets (at most 2 distinct fruit types) using a sliding window.
Find the maximum sum of a subarray with all unique elements using a sliding window backed by a HashSet.
Find the smallest subarray with sum >= target using a variable sliding window that shrinks from the left when the condition is met.
Count tuples (i,j,k,l) where nums1[i]+nums2[j]+nums3[k]+nums4[l]=0 by hashing all pairs from first two arrays.
Maximize water trapped between two vertical lines using inward two pointers that always move the shorter line inward.
Find minimum boats to save everyone where each boat carries at most 2 people with total weight <= limit, using sort + greedy two pointers.
Find all unique triplets summing to zero by sorting and using two pointers for each fixed element with careful duplicate skipping.
Find two numbers summing to target in a 1-indexed sorted array using inward two pointers in O(n) time O(1) space.
Count contiguous subarrays with product < k using a sliding window that divides from the left when product exceeds the limit.
Maximize card points taken from both ends of an array by finding the minimum-sum subarray of size n-k in the middle.
Count subarrays with exactly k odd numbers using the at-most(k) minus at-most(k-1) sliding window formula.
Count binary subarrays with exactly the given sum using prefix sum with HashMap or the atMost(k)-atMost(k-1) trick.
Find the maximum frequency of any element after at most k increments by sorting and using a sliding window with a running sum.
Find minimum operations to reduce X to zero from either end by finding the longest middle subarray with sum = total-X.
Find the longest mountain subarray (strictly increasing then decreasing) using two separate forward scans for up and down slopes.
Find the longest turbulent subarray where comparisons alternate between > and < using two-pointer direction tracking.
Count subarrays with exactly K distinct integers using the mathematical trick: exactly(K) = atMost(K) - atMost(K-1).
Find the minimum length substring to replace so that a string of QWER has equal frequencies, using a shrinkable two-pointer approach.
Find minimum character flips to make a binary string alternating by applying a fixed circular sliding window of size n.
Find the maximum number of vowels in any substring of length k using a fixed sliding window with vowel count.
Find minimum swaps to group all 1s together in a circular binary array using a fixed-size sliding window equal to the count of 1s.
Find minimum minutes to collect at least k of each character from ends by finding the longest middle window that can be excluded.
Maximize customer satisfaction by finding the best k-minute window for the bookstore owner to stay non-grumpy.
Find the minimum difference between the max and min of any k scores by sorting and using a fixed window of size k.
Find the maximum length substring you can transform from s to t within a given cost budget using a sliding window on character change costs.
Count substrings containing at least one a, b, and c using the last-seen indices shortcut for O(n) time.
Count subarrays with sum divisible by k using prefix sum modulo k and a frequency map of remainders.
Find k closest integers to x in a sorted array using binary search to locate the optimal left boundary of the window.
Count subarrays where min=minK and max=maxK using a single pass tracking the last invalid position and last positions of minK and maxK.
Find the maximum consecutive ones in a binary array when you can flip at most k zeros, identical to the Max Consecutive Ones III pattern.
Sort only the vowels in a string while keeping consonants in place by extracting vowels, sorting, then reinserting.
Find the minimum window in s that contains t as a subsequence by using a forward pass to find a valid window then backward pass to minimize it.
Count subarrays where the median is exactly k by converting the problem to counting balanced prefix sequences around k.
Find the median of each sliding window of size k using two heaps (max-heap for lower half, min-heap for upper half) with lazy deletion.
Find all starting indices of substrings that are concatenations of all given words using a sliding window for each possible word-aligned start.
Find the minimum number of consecutive cards that contain a matching pair using a HashMap tracking last seen positions.
Count subarrays where score = sum × length is less than k using a shrinkable sliding window with running sum.
Find the smallest window in s containing all characters of t using a have/need counter to track when the window is valid.
Find the maximum in every sliding window of size k in O(n) using a monotonic decreasing deque of indices.
Find the shortest subarray with sum >= k, handling negative numbers correctly using a monotonic deque on prefix sums.
Find the longest substring containing at most 2 distinct characters using a variable sliding window with a character count map.
Find the longest contiguous subarray of 1s after deleting exactly one element using a sliding window allowing at most one zero.
Sort an array of 0s, 1s, and 2s in one pass using the Dutch National Flag 3-pointer algorithm.
Check if a string can become a palindrome by deleting at most one character using recursive two-pointer palindrome checking.
Check if an array can be split into three consecutive parts with equal sum using a greedy counting approach.
Calculate trapped rainwater using optimal two-pointer approach that tracks left and right maximums without extra space.
Complete cheatsheet of Two Pointers and Sliding Window patterns with template code, problem index, and MAANG priority list.
Comprehensive palindrome problem coverage: valid palindrome check, longest palindromic substring (three methods), count palindromic substrings, and palindrome partitioning.
Implement run-length encoding, string compression in-place, and decode compressed strings. Tests two-pointer technique and string manipulation.
Search for a target in a matrix where each row and column is sorted. O(m+n) solution using top-right corner elimination — a classic Google interview problem.
Find the smallest substring of s containing all characters of t using an expanding/contracting two-pointer window with frequency counting. O(n) time.
Comprehensive coverage of Two Sum, Two Sum II (sorted), 3Sum, and 4Sum. Amazon frequently tests these variants to gauge understanding of hashmap vs two-pointer trade-offs.