Contains Duplicate II

EasyArrays & Hashingsliding window

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an integer array nums and an integer k, return true if there exist two **different** indices i and j with nums[i] == nums[j] and abs(i - j) <= k. Otherwise return false. In other words, decide whether some value repeats within a distance of at most k positions. Aim for O(n) time.

Examples

Input: nums = [1,2,3,1], k = 3
Output: true
The two 1s are at indices 0 and 3, which are 3 apart.
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
Every repeated value is exactly 3 positions from its twin, more than k = 2.
Input: nums = [1,0,1,1], k = 1
Output: true
Indices 2 and 3 both hold 1 and are adjacent.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • 0 <= k <= 10^5

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More sliding window problems