A building's turnstile logs every badge scan in order as visitors walk through, recording one integer badge number per scan. Security wants to know how tightly a duplicate scan can be bounded: the shortest contiguous stretch of the log (a run of consecutive scans, with none skipped) that contains the same badge number appearing at least twice inside it.
Given the sequence of badge numbers scanned, find the length of the shortest such contiguous stretch. If no badge number is ever scanned twice, report that no such stretch exists.
Line 1: a single integer n — the number of scans. Line 2: n space-separated integers b_1, b_2, ..., b_n — the badge number recorded at each scan, in scan order.
Print a single integer: the length of the shortest contiguous stretch of scans containing a repeated badge number, or -1 if every badge number appears at most once in the log.
Example 1
Input
8 3 1 4 1 5 9 2 6
Expected
3
Explanation
Badge 1 is scanned at position 2 and again at position 4 (1-indexed), a stretch of length 4 - 2 + 1 = 3, namely the scans [1, 4, 1]. No other badge number repeats anywhere in the log, so 3 is the shortest possible stretch.
Example 2
Input
5 1 2 3 4 5
Expected
-1
Explanation
Every badge number from 1 to 5 is scanned exactly once, so no two scans share a badge number and no qualifying stretch exists — the answer is -1.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →