The foundation of coding interviews. 40+ highly-asked questions with complete solutions. Focus: Two Pointers, Sliding Window, and O(1) space optimizations.
Optimal Technique: Hash Map (or Dictionary). This approach allows us to reduce the search time from O(n) (in a brute force approach) to O(1) for each element, achieving an overall time complexity of O(n).
Steps:
numMap to store (number, index) pairs encountered so far.num, calculate the complement = target - num.complement already exists as a key in numMap. If it does, we have found the pair. Return [numMap[complement], current_index].numMap[num] = current_index.Complexity: Time: O(n). Space: O(n).
Optimal Technique: Two-Pointer approach. Start with pointers at the extreme ends (widest possible container) and greedily move the pointer associated with the shorter line inward.
Rationale: The area is calculated as $Area = \min(\text{height}[\text{left}], \text{height}[\text{right}]) \times (\text{right} - \text{left})$. Starting wide maximizes the width. To increase the area, you must increase the minimum height. Moving the shorter line gives a better chance of finding a taller boundary compared to moving the already taller one (which would only reduce the width).
Complexity: Time: O(n). Space: O(1).
Technique: Three-pointer Partition (Dijkstra's Three-Way Partitioning). Use three pointers: low (boundary for 0s), mid (current element), and high (boundary for 2s).
arr[mid] == 0: Swap arr[mid] and arr[low], increment low and mid.arr[mid] == 1: Increment mid.arr[mid] == 2: Swap arr[mid] and arr[high], and decrement high. Crucially, **do not increment mid** because the element swapped from high needs to be checked.Complexity: Time: O(n). Space: O(1).
Technique: Sliding Window. Use a Hash Set (or a Map) to efficiently track the characters currently present within the window defined by two pointers, left and right.
Process:
right pointer forward and adding s[right] to the set.s[right] is already in the set (duplicate found), shrink the window by moving the left pointer forward and removing s[left] from the set until the duplicate is gone.Complexity: Time: O(n). Space: O(min(n, alphabet\_size)).
Technique: Advanced Sliding Window with two Frequency Maps. This uses a "needed" map (for target string T) and a "window" map (for current string S). A crucial variable, formed, tracks how many unique characters in T are matched in the window S.
Process:
right pointer, updating the window map. Check if the character count now satisfies the need. If so, increment formed.formed equals the total number of unique characters needed, you have a valid window. Contract the window by moving the left pointer forward until validity is broken. Update the global minimum length during this contraction phase.Complexity: Time: O(|S| + |T|). Space: O(alphabet\_size).