LeetCode: Contains Duplicate II Solution
TrickyApproach
Use hash table to store the latest index for num
This make sure i - j
will always be positive and smallest at the iterating time
Implementation
1var containsNearbyDuplicate = function (nums, k) {2 const map = {}34 for (const [i, num] of nums.entries()) {5 const j = map[num]6 if (j !== undefined && i - j <= k) {7 return true8 }910 map[num] = i11 }1213 return false14}
Similar problems
Contains Duplicate III
Comments
Loading comments...
Tags
leetcode
array
hash table
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Intersection of Two Arrays
Set intersection
Previous Post
LeetCode: Summary Ranges
Straight forward checking