KatInterview

Longest Run of Non-Repeating Numbers in an Array

Arrays & HashingAuto-graded · 18 test cases
MediumAuto-gradedArrays & Hashingsliding-windowhash-maptwo-pointers

Last updated

Find the length of the longest contiguous stretch of an integer array in which no value appears twice, using a sliding window with a last-seen index map.

Longest Run Without Repeats

You are given a list of integers values. A run is a contiguous block of elements (a subarray). A run is repeat-free if no number occurs more than once inside it.

Return the length of the longest repeat-free run in values.

Rules

  • The run must be contiguous: the elements must be adjacent in the original list, in their original order.
  • If values is empty, return 0.
  • If every element is the same, the answer is 1.
  • If all elements are different, the answer is len(values).
  • Only the length is returned, not the run itself.

Constraints

  • 0 <= len(values) <= 10^5
  • -10^9 <= values[i] <= 10^9
  • Aim for a solution that runs in roughly linear time.

Examples

Example 1

Input: longest_repeat_free_run([1, 2, 3, 1, 4, 5])

Output: 5

Example 2

Input: longest_repeat_free_run([7, 7, 7, 7])

Output: 1

Hints

Hint 1

Think of a window [left, right] that always contains distinct values. Extend right one step at a time and decide how far left must move when a duplicate shows up.

Hint 2

Store, for each value, the last index at which it appeared. When the new value's previous index is inside the window, move left to just after that index.

Hint 3

Be careful with stale entries: only move left if the previous index is at least left (or use left = max(left, last_index + 1)), so the left boundary never moves backwards.