Skip to content

28 of 32 · 6 min

Two indices instead of two loops

A nested loop over an array is O(n squared). A surprising number of those can be done in one pass with two indices, and recognising which is one of the highest value skills in an interview.

Two pointers on sorted data

Find two numbers in a sorted array that add to a target.

The nested loop tries every pair. Instead, start at both ends:

python
def two_sum_sorted(nums, target):
    left, right = 0, len(nums) - 1
    while left < right:
        total = nums[left] + nums[right]
        if total == target:
            return (left, right)
        if total < target:
            left += 1      # need more, smallest is too small
        else:
            right -= 1     # need less, largest is too large
    return None

Every step discards one element permanently, so the whole thing is O(n).

The reason it is safe is worth stating, because it is what the interviewer is checking: if the sum is too small, the smallest element cannot be part of any valid pair with anything remaining, since everything left is even smaller than the one being dropped. Sortedness is what licenses that.

Sliding window on contiguous ranges

When the question asks about a contiguous stretch, grow a window on the right and shrink it on the left.

Longest stretch with no repeated character:

python
def longest_unique(s):
    seen = {}
    best = start = 0
    for end, ch in enumerate(s):
        if ch in seen and seen[ch] >= start:
            start = seen[ch] + 1
        seen[ch] = end
        best = max(best, end - start + 1)
    return best

Each index enters the window once and leaves once, so it is O(n) despite looking like it has two moving parts.

Which technique, from the question

The question saysReach for
sorted, find a pair or tripletwo pointers from both ends
contiguous, longest or smallestsliding window
contiguous, sum equals kprefix sums with a hash map
not contiguous, any subsetthis is usually dynamic programming

That last row is the distinction to be careful with. Subarray means contiguous and a window works. Subsequence means elements may be skipped, the window does not apply, and the answer is a table.