Question Bank
Two-Pointer Warm-Up
Difficulty: Easy
Four short prompts covering pair sums, in-place dedupe, and palindrome checks with two pointers. Great preparation before sliding-window drills.
Two-Pointer Warm-Up
Four short prompts covering pair sums, in-place dedupe, and palindrome checks with two pointers. Great preparation before sliding-window drills.
946 views
31
Implement hasPairSum(sortedArr, target) that returns true if any two distinct elements in the sorted array sum to target. Use the two-pointer technique in O(n) time.
Examples
Example 1:
Input: sortedArr = [1, 2, 4, 7, 11], target = 9
Output: true
Explanation: lo = 0, hi = 4. Sum 1 + 11 = 12 > 9, hi--. Sum 1 + 7 = 8 < 9, lo++. Sum 2 + 7 = 9, return true.Example 2:
Input: sortedArr = [1, 2, 4, 7, 11], target = 20
Output: false
Explanation: The pointers converge without ever hitting the target, so the function returns false. O(n) time, O(1) space.Implement removeDuplicates(arr) for a sorted array. Modify in place so the first k elements are unique, and return k. Extra space must be O(1).
Examples
Example 1:
Input: arr = [1, 1, 2, 2, 3, 4, 4]
Output: 4; the first 4 entries of arr are [1, 2, 3, 4]
Explanation: Slow pointer k tracks the next write slot; fast pointer i scans the array. Whenever arr[i] differs from arr[k - 1], copy it to arr[k] and bump k. O(n) time, O(1) space.Trace what isPalindrome('A man a plan a canal Panama') should return after lowercasing and stripping non-alphanumerics, and explain how to do that check with two pointers without building a cleaned copy.
Spot the bug. moveZeroes(arr) should push every 0 to the end while preserving the order of non-zeroes, in place. The version below loses elements on some inputs.
Examples
Example 1:
Input: arr = [1, 0, 2, 0, 3]
Output (buggy version): [1, 2, 3, 0, 3]
Output (fixed version): [1, 2, 3, 0, 0]
Explanation: The non-zero copy phase is correct, but the buggy version never zero-fills the tail past write. The fix either zero-fills [write..n) or swaps arr[read] with arr[write] on each non-zero, which leaves trailing zeros in place automatically.