Skip to content

Closest Repeat Distance

Easy#hash-map#single-pass~15 min

The mission

Problem

You are given a list of values. Among all pairs of positions that hold the same value, find the pair that sits closest together and return the gap between them, measured as the difference of their indexes. If no value appears twice, return -1.

Examples

Input:  values = [7, 1, 3, 7, 1, 7]
Output: 2
Why:    the 7s at indexes 3 and 5 are two apart; the 1s are three apart
Input:  values = [3, 8, 8, 3]
Output: 1
Why:    the two 8s sit side by side
Input:  values = [5, 6, 7]
Output: -1
Why:    edge case, nothing repeats

Hints

0 / 3

Target time
O(n)
Target space
O(n)

Stuck on the idea rather than the code? What Is Big-O? covers it.

Python 3Ctrl+Enter runs
Custom test case