DSA · Hash Table · #57
Contains Duplicate II
Module 54 · difficulty 2/5·⏱ 30:00starts on first keystroke
Given an integer array `nums` and an integer `k`, return `true` if there are two **distinct** indices `i` and `j` in the array such that `nums[i] === nums[j]` and `Math.abs(i - j) <= k`. Otherwise return `false`. Implement the function `containsNearbyDuplicate(nums, k)`.
Examples
nums = [1,2,3,1], k = 3→true— nums[0] === nums[3] === 1 and abs(0 - 3) = 3 <= 3.nums = [1,0,1,1], k = 1→true— nums[2] === nums[3] === 1 and abs(2 - 3) = 1 <= 1.nums = [1,2,3,1,2,3], k = 2→false— Every duplicate pair is more than 2 indices apart.
Constraints
- · 1 <= nums.length <= 10^5
- · -10^9 <= nums[i] <= 10^9
- · 0 <= k <= 10^5
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.