DSA Factory
Free Arrays lessonsArrays · Stage 6 · Arrays and hashing · Step 1

Remember where you first saw it

Keep the first position of every value in a map. About 8 minutes.

A notebook of first sightings

Birdwatchers keep a log: the first time they spot each kind of bird, they note the date. Later, when they see that bird again, they can say how long it's been since the first sighting.

A map works as that log. The key is a number from the array, and the value is the box where you first saw it. When you meet a number that's already in the log, the gap back to its first sighting is how far apart the two copies are.

New number? note where you first saw it.
Seen it before? the gap is how far apart they are.
One pass, remembering first positions
3
0
1
1
4
2
1
3
5
4
3
5
j

3 is new: note that it was first seen in box 0.

Move 1 of 6

Never overwrite the first sighting

You want the pair of equal values that's as far apart as possible. For any later copy, the copy furthest to the left gives the biggest gap. So once a number is in the log, leave its entry alone.

Updating it to the latest sighting would shrink every gap you measure afterwards. The answer for 3, 1, 4, 1, 5, 3 is 5, the two 3s at the ends.

Keep the first sighting: updating it shrinks the gaps.
In code
first = {}
best = 0
for j, x in enumerate(nums):
    if x in first:
        best = max(best, j - first[x])
    else:
        first[x] = j
return best
Quick check

In 2, 7, 2, 2, the walk reaches the last 2 (box 3). What gap does it measure?

  1. A3
  2. B1
  3. C2
Show the answer

3. The log still says the first 2 was in box 0, so the gap is 3.

Your problem

Widest equal pair

You get a list of numbers. Find two positions i < j holding the same value, as far apart as possible, and return j − i. If no value appears twice, return 0.

Example
nums = [3, 1, 4, 1, 5, 3] → 5

0 ≤ n ≤ 1,000,000 · −1,000,000,000 ≤ each value ≤ 1,000,000,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve