Hard 1: lists, strings and search
These are the problems interviewers reach for when the easy ones are done. Each combines two ideas from the lessons: a window with a counter, a sort with two pointers, a binary search over answers rather than items. Read the whole statement, including the paragraph after the examples; it names the technique.
Smallest window containing every letter
Write min_window(text, letters) that returns the shortest stretch of text that
contains every character of letters, including repeats, or "" if none does. If several
stretches tie for shortest, return the leftmost.
min_window("ADOBECODEBANC", "ABC") -> "BANC"
min_window("a", "aa") -> ""
A variable window with a Counter of what is still needed and a count of how many
requirements are unmet. Grow from the right until everything is covered, shrink from the
left while it stays covered. One check is a hundred thousand characters.
def min_window(text, letters):
...
Smallest missing positive
Write first_missing(nums) that returns the smallest positive whole number not in the
list. The classic version uses the list itself as the hash table so that extra memory is
constant; a set also passes.
first_missing([1, 2, 0]) -> 3
first_missing([3, 4, -1, 1]) -> 2
first_missing([7, 8, 9]) -> 1
The answer is between 1 and len + 1. Put each value v in that range at index v - 1
by swapping, then scan for the first index whose value is wrong.
def first_missing(nums):
...
Longest palindromic stretch
Write longest_palindrome(text) that returns the longest stretch of consecutive
characters that reads the same backwards. If several tie, return the leftmost.
longest_palindrome("babad") -> "bab"
longest_palindrome("cbbd") -> "bb"
longest_palindrome("") -> ""
Expand around every centre, both a single character and the gap between two characters. Quadratic in the worst case, which is fine for a few thousand characters.
def longest_palindrome(text):
...
Three sum, distinct triplets
Write three_sum(nums) that returns every distinct triplet [a, b, c] with a <= b <= c
from the list that sums to zero, each triplet using three different positions. Order of
the output does not matter.
three_sum([-1, 0, 1, 2, -1, -4]) -> [[-1, -1, 2], [-1, 0, 1]]
three_sum([0, 0, 0, 0]) -> [[0, 0, 0]]
three_sum([1, 2]) -> []
Sort, fix the first element, two pointers for the other two, and skip duplicates on all three. Quadratic; a triple loop will not finish the largest check.
def three_sum(nums):
...
Largest product of a run
Write max_product(nums) that returns the largest product of any non-empty run of
consecutive items. Values may be negative or zero.
max_product([2, 3, -2, 4]) -> 6
max_product([-2, 0, -1]) -> 0
max_product([-2, 3, -4]) -> 24
Track both the largest and the smallest product of a run ending at each position: a negative number turns the smallest into the largest.
def max_product(nums):
...
Longest balanced bracket stretch
Write longest_valid(text) that returns the length of the longest stretch of text,
made only of ( and ), that is a correctly balanced bracket string.
longest_valid("(()") -> 2
longest_valid(")()())") -> 4
longest_valid("") -> 0
A stack of indices with a sentinel: push on (, pop on ), and the length of the
current valid stretch is the distance from the current index to the top of the stack.
def longest_valid(text):
...
Median of two sorted lists
Write median(a, b) that returns the median of all values in two sorted lists combined
(the middle value, or the average of the two middles), as a float. At least one list is
non-empty.
median([1, 3], [2]) -> 2.0
median([1, 2], [3, 4]) -> 2.5
median([], [1]) -> 1.0
Merging is linear and passes. The interview answer binary-searches how many items of the shorter list belong in the left half, which is logarithmic; try it once the merge works.
def median(a, b):
...
k-th smallest in a sorted matrix
matrix is a list of rows where every row and every column is sorted ascending. Write
kth_smallest(matrix, k) that returns the k-th smallest value overall, counting repeats.
kth_smallest([[1, 5, 9], [10, 11, 13], [12, 13, 15]], 8) -> 13
kth_smallest([[-5]], 1) -> -5
Two good routes: a heap merging the rows (k log n), or binary search on the value with a linear count of how many entries are at most the guess. Flattening and sorting also passes.
def kth_smallest(matrix, k):
...
Split into k pieces, minimise the largest
Write min_largest_sum(nums, k) that splits the non-negative list into k non-empty
consecutive pieces so that the largest piece sum is as small as possible, and returns
that sum.
min_largest_sum([7, 2, 5, 10, 8], 2) -> 18
min_largest_sum([1, 2, 3, 4, 5], 2) -> 9
min_largest_sum([1, 4, 4], 3) -> 4
Binary search on the answer: for a candidate maximum, greedily count how many pieces are
needed; if at most k, the candidate is achievable.
def min_largest_sum(nums, k):
...
Count smaller items to the right
Write smaller_to_right(nums) that returns a list where entry i is how many items to the
right of position i are smaller than nums[i].
smaller_to_right([5, 2, 6, 1]) -> [2, 1, 1, 0]
smaller_to_right([-1, -1]) -> [0, 0]
The pairwise loop is quadratic and passes the small checks. The fast version is merge
sort on (value, original index) pairs, counting how many right-half items jump past each
left-half item during the merge. One check has forty thousand items.
def smaller_to_right(nums):
...