Nine interview problems where only presence matters, and memory or order is tight. The move: decide where 'seen before?' is answered, in a set, in the array itself or in a next link.
You work on a feed app, a ride-hailing app, a chat service and a maps app. The problems on this street come from all four. Each one asks whether an id has been seen. None of them asks how often.
The twist is a limit. Sometimes memory is tiny, sometimes the list must not be changed, and sometimes a separator may appear in the data. Here is each problem and where the answer to "seen before?" can live.
| Problem | The limit | Where "seen before?" lives |
|---|---|---|
| Happy ids that reach one | none, but a walk can loop | a set of earlier values |
| Intersection of two feed lists | each id once, in list order | a set of the other list |
| Sum of unique elements | exactly once, not twice | counts, with three states |
| Find the duplicate in a read-only list | no changes, tiny memory | the value as a next index |
| Longest chain of linked ids | links come in any order | a map from id to next id |
| Distinct senders in the last few seconds | the window is a stretch of time | a count for each id in the window |
| Longest tour on a circular trail | the list is a loop | the last position of each id |
| Encode and decode a list of strings | any character may appear | a length written first |
| First missing positive id | only the list itself | the slot named by the value |
Read the last column. The first rows use a hash set, and the later rows give it up for something cheaper.
A set always works, and it costs memory in proportion to the list. Before you reach for it, ask what the problem allows.
Each id is looked up where its history already lives: a hash set, the array slot its value names, or its own next link. So one pass visits each id once, with no extra scan.
There are three homes, and each one needs a different promise from the input.
| Home | The promise it needs | The extra memory |
|---|---|---|
| A hash set | none | one entry per id |
| The array itself | every value is a valid slot, or can be ignored | a few numbers |
| A next link | every value is a valid index, with a repeat | two pointers |
The third home is the odd one. The list 1, 3, 4, 2, 2 holds five values between 1 and 4. Treat each value as the index of the next cell.
From index 0 you go to 1, 3, 2, 4, then back to 2. So the walk enters a cycle, and the cell where it enters is the repeated value.
Exercise · Predict the output: Where does the walk enter the cycle?. The values are used as next indexes. The first loop moves slow by one step and fast by two until they meet. The second loop restarts slow at index 0. What does it print?
nums = [1, 3, 4, 2, 2]
slow = 0
fast = 0
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
slow = 0
while slow != fast:
slow = nums[slow]
fast = nums[fast]
print(slow)Treat each value as the index of the next cell. A repeated value makes a cycle, and the cycle entry is the repeat.
The Academy lesson Seen-set and complement builds the set, and Hash table internals says what it costs. Fast and slow pointers walks a list with two speeds, and Strings and builders builds text. This street changes four things.
The set may be too expensive. A read-only list with a tiny memory cannot be copied into a set or marked. The cycle walk in the prediction needs two integers and no change to the list.
The array can be the set. For the first missing positive, the answer is between 1 and n + 1, so a value v outside 1 to n is ignored. A value in range is swapped to slot v - 1. The first slot that does not hold its own number names the answer.
A single swap per position is not enough. After a swap, the new value at the same position may belong elsewhere too. On the list 3, 4, -1, 1 one swap per position gives the answer 1, but the right answer is 2.
Exercise · Find the bug: One swap is not enough. This puts every value from 1 to n into the slot named by its value, then returns the first slot that is wrong. It is right for many lists but not all. Which line is wrong?
def first_missing(nums):
n = len(nums)
for i in range(n):
if 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]:
j = nums[i] - 1
nums[i], nums[j] = nums[j], nums[i]
for i in range(n):
if nums[i] != i + 1:
return i + 1
return n + 1A swap brings a new value into the same position, so repeat the swap until the slot is settled.
A chain is walked from its head. Links source, copy form chains. Walking from every message re-walks each chain, and for one chain of 50,000 messages that costs 1,249,975,000 steps. Walking only from heads, the messages that are no copy of any earlier message, reads each message once.
A sequence needs a length, not a delimiter. Two strings, a#b and c, joined with a hash and split again become three pieces: a, b and c. Written as 3#a#b1#c, the packet gives the length first, so the reader takes exactly three characters and the hash inside the text does no harm.
Happy ids stay small. One step of digit squares sends any id below 1,000,000 to at most 486. For every id up to 300,000 the walk reaches 1 or repeats within 20 steps.
Exercise · Break it: Whose order is it?. This returns the ids that appear in both lists, each once. It keeps the first list in a set and walks the second list. The task wants the order of the first list. Find an input where it is wrong.
def shared_ids(first, second):
in_first = set(first)
done = set()
result = []
for x in second:
if x in in_first and x not in done:
result.append(x)
done.add(x)
return resultSolve them in this order. The first three use a set, the next three give it up for a cheaper home, and the last is the hardest of them.
Before you code each problem, write two lines: where the answer to "seen before?" will live, and what the problem forbids that rules out the set. If it forbids nothing, a set is the right start.
Give each problem about 20 minutes. Spend the first three on the two lines, and then write the set solution anyway when memory is tight. Compare what it costs with what the problem allows.
Three edge cases come back on most rungs. The list can be empty, every value can be the same, and a value can be out of range. Write one small test for each before you run anything.
When a solution fails, check the home of "seen before?" first. Most wrong answers on this street come from a single swap where a loop is needed, or from a walk that starts from every id.
Checkpoint · Sequences and sets
Q1/5 A list is read-only and memory is tiny. Which home for "seen before?" can still work?
Answer: C
A read-only list cannot be marked, and a set or a copy needs memory in proportion to the list. The walk needs only two pointers.
Q2/5 In the cycle walk on 1, 3, 4, 2, 2, the first loop ends where the two pointers meet. Is that cell the repeated value?
Answer: B
The pointers meet at index 4, and the repeated value is 2. Restarting one pointer at index 0 and moving both by one step finds the entry.
Q3/5 Placing each value v into slot v - 1 uses a while loop and not an if. Why?
Answer: C
On 3, 4, -1, 1 a single swap per position leaves a value misplaced, and the code answers 1 instead of 2.
Q4/5 Where do you start walking when you look for the longest chain of linked ids?
Answer: C
Starting at heads walks each chain once. Starting at every id re-walks each chain, which is 1,249,975,000 steps for one chain of 50,000.
Q5/5 The strings a#b and c are joined with # and split on #. How many pieces come back?
Answer: B
The text a#b holds the delimiter, so the split gives a, b and c. Writing the length first, as 3#a#b1#c, avoids the problem.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.