Find the Single Repeated Value Among n + 1 Integers Drawn from 1 to n
Company: Walmart Labs
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Onsite
Overview: Given an array of n + 1 integers whose values all lie between 1 and n, return the one value that repeats, possibly several times. The challenge is solving it without modifying the array and with constant extra memory, which rules out sorting, hash sets and counting arrays.
Constraints
- 1 <= n <= 10^5
- nums.length == n + 1
- 1 <= nums[i] <= n
- Exactly one value appears two or more times; every other value from 1 to n appears at most once, and some may not appear at all.
- nums must be left unchanged, and extra memory must not grow with n.
Examples
Input: ([1, 1],)
Expected Output: 1
Explanation: Minimum valid input: n = 1, so both entries must be 1.
Input: ([4, 1, 3, 2, 4],)
Expected Output: 4
Explanation: Source example 1: n = 4, the repeated value equals n and sits at the first and last positions.
Hints
- There are n + 1 entries but only n possible values, so a repeat is guaranteed; think about what that same counting argument says about smaller ranges of values.
- Since nums is read-only and memory must stay constant, everything you track has to fit in a few integer variables, though reading the array several times is allowed.
- Every value lies between 1 and n, so each value is also a valid index into nums.