Problems on a row of numbers
After this: Solve binary search and best day to buy and sell, and recall two sum, each with its cost.
On this page · 6 sections · 3 checks
In an interview you often get a problem you have met before, in new words. If you recognise its shape, you can name the tool and write code you have written before. This tutorial works ten problems that interviewers ask again and again, so that their shapes become familiar.
How each problem is worked
Every problem in this tutorial is worked in the same five parts, in this order:
- The pattern, named first. A is a way of solving a whole family of problems. Try to name it yourself before you read on.
- The idea, in two or three sentences.
- The solution, in Python and Java.
- The cost in words: how the work grows, as in Counting steps, and how much the solution needs on top of its input. O(n) means the amount grows with the size of the input; O(1) means it stays the same however big the input is.
- A pinned example: an input and the output it gives, run in both languages.
This lesson has three problems on a row of numbers. You met the first in Solving a problem you have not seen.
1. Two sum (a recap)
The problem: return the positions of two numbers that add up to a target. Pattern: a hash map. Go through the numbers once, and keep a map from each number seen so far to its position. For each new number, look up the partner it needs.
two_sum([3, 2, 4], 6)twoSum(new int[] {3, 2, 4}, 6) gives [1, 2], because 2 + 4 = 6, in one pass: O(n) time and O(n) extra memory for the map.
2. Binary search on a sorted list
Pattern: binary search. Look at the middle. If the target is bigger, it can only be in the right half; if smaller, only in the left half. Each look throws away half of what is left.
def search(nums, target): lo, hi = 0, len(nums) - 1 while lo <= hi: mid = (lo + hi) // 2 if nums[mid] == target: return mid if nums[mid] < target: lo = mid + 1 else: hi = mid - 1 return -1static int search(int[] nums, int target) { int lo = 0, hi = nums.length - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (nums[mid] == target) { return mid; } if (nums[mid] < target) { lo = mid + 1; } else { hi = mid - 1; } } return -1;}lo and hi mark the part of the row that can still hold the target. mid is the middle of that part. A hit returns mid. Otherwise one end moves past mid, so the part shrinks every time. When lo passes hi, nothing is left, and the function returns -1.
Pinned example. In [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] the target 23 is found at index 5. The probes read 16 (too small, go right), 56 (too big, go left), then 23. The target 40 gives -1, and so does an empty list.
Cost. Each probe halves the part that is left, so the work grows with log n: the number of times you can halve n before one item is left. That is O(log n). Ten items need at most 4 probes, and a million need about 20. Extra memory: O(1), which means a fixed amount however long the row is; here, three numbers.
- Binary search for 23Search for 23. Watch lo and hi close in: the probes read 16, then 56, then 23.
- Binary search for 40
- 02
- 15
- 28
- 312
- 416
- 523
- 638
- 756
- 872
- 991
Run an operation to begin.
3. Best day to buy and sell
Think of the prices [8, 3, 6, 1, 4, 7, 2] before you read on. The best plan is to buy at 1 and sell at 7, for a profit of 6. Selling at 8 is no good, because 8 comes first.
The tries every buy day with every later sell day. That is about n × n ÷ 2 pairs, O(n²): double the days and the work goes up about four times.
Pattern: one pass, remembering the lowest price so far. For any sell day, the best buy day is the cheapest day before it. So go through the days once, keep the lowest price seen so far in one box, and on each day ask: what if I sold today?
- Run the programRun it and step through. Watch two boxes: lowest, the cheapest day so far, and best, the biggest profit so far. Note the day each one changes.
def max_profit(prices): lowest = float("inf") best = 0 for p in prices: lowest = min(lowest, p) best = max(best, p - lowest) return best
print(max_profit([8, 3, 6, 1, 4, 7, 2]))run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
Follow the two boxes:
- Day 1 (8):
lowestbecomes 8. Selling today makes 0. - Day 2 (3):
lowestbecomes 3. - Day 3 (6): 6 − 3 = 3, so
bestbecomes 3. - Day 4 (1):
lowestbecomes 1. - Day 6 (7): 7 − 1 = 6, so
bestbecomes 6. Days 5 and 7 change nothing.
The function returns 6. For [9, 7, 4, 1] it returns 0: every day is cheaper than the one before, so there is never a profit.
Cost. One pass: O(n) time, which means the work grows with the number of days. Extra memory: O(1), two boxes, however many days there are.
Run it
Java does not run here. Step through the Java with the trace above, or paste the Java into a Java tool on your computer. The Python below runs all three solutions on their pinned examples.
Try your own prices, and an edge case such as a single day.
Check yourself
You get the price of one share for each day. You may buy once and sell once, on a later day. Which pattern finds the biggest profit in one pass?
Searching the row for 23. The first probe reads index 4, which holds 16. Where are lo and hi after it?
The price falls every day. What does this print?
def max_profit(prices): lowest = float("inf") best = 0 for p in prices: lowest = min(lowest, p) best = max(best, p - lowest) return best
print(max_profit([9, 7, 4, 1]))public class Main { static int maxProfit(int[] prices) { int lowest = Integer.MAX_VALUE; int best = 0; for (int p : prices) { lowest = Math.min(lowest, p); best = Math.max(best, p - lowest); } return best; }
public static void main(String[] args) { System.out.println(maxProfit(new int[] {9, 7, 4, 1})); }}- Work every problem in the same order: name the pattern first, then the idea, the code, the cost in words and a pinned example.
- Recall two sum: one pass with a hash map from each number seen to its position, O(n) time and O(n) extra memory.
- Write binary search with lo, hi and mid, and say why it costs O(log n): each probe halves what is left, so ten items need at most four probes.
- Solve best day to buy and sell in one pass by remembering the lowest price so far and the best profit so far: O(n) time, O(1) extra memory.