Maps app~25 min2s · 256 MBtarget O(n) time, O(n) spacehashing
You work on a maps app that offers walking tours. A circular trail has viewpoints in a row, numbered from 0, and each viewpoint shows one landmark. A landmark has a code, and different viewpoints can show the same landmark.
A tour starts at any viewpoint and walks forward along the trail, past the last viewpoint to viewpoint 0 again if it likes, for at most one lap. Visitors dislike seeing a landmark twice. Your team lead asks: "What is the longest tour without a repeated landmark?"
Write longest_clear_stretch(codes).
codes[i] is the landmark code at viewpoint i. After viewpoint n - 1 comes viewpoint 0.n. It visits the viewpoints in order, wrapping from the last to the first.[length, start] for the longest clear tour. When several tours have the longest length, return the one with the smallest start.Input: codes = [5, 1, 3, 1, 2, 4]
Output: [5, 2]The best tour starts at viewpoint 2 and visits viewpoints 2, 3, 4, 5 and 0, with the codes 3, 1, 2, 4, 5. It passes the last viewpoint. Without the wrap the best tour has length 4.
| Right edge (position in two laps) | Code | Left edge after | Window length | Best so far |
|---|---|---|---|---|
| 0 | 5 | 0 | 1 | 1 at start 0 |
| 1 | 1 | 0 | 2 | 2 at start 0 |
| 2 | 3 | 0 | 3 | 3 at start 0 |
| 3 | 1 | 2 | 2 | 3 at start 0 |
| 4 | 2 | 2 | 3 | 3 at start 0 |
| 5 | 4 | 2 | 4 | 4 at start 2 |
| 6 | 5 | 2 | 5 | 5 at start 2 |
The window of length 5 at right edge 8 starts at viewpoint 4. It is not longer, so the answer keeps start 2.
Input: codes = [7]
Output: [1, 0]Input: codes = [4, 4, 4]
Output: [1, 0]Every tour of length 2 repeats the code, so the best length is 1, and the smallest start is 0.
1 ≤ codes.length ≤ 100,000 (viewpoints)1 ≤ codes[i] ≤ 1,000,000Starting a tour at each viewpoint and walking until a repeat can take a whole lap each time. That is 100,000 × 100,000 = 10,000,000,000 steps when all codes differ.
A window that slides along the trail twice, with the last place of each code in a hash map, needs about 200,000 steps.