LeetCode: Contains Duplicate II Solution

Tricky

Approach

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 = {}
3
4 for (const [i, num] of nums.entries()) {
5 const j = map[num]
6 if (j !== undefined && i - j <= k) {
7 return true
8 }
9
10 map[num] = i
11 }
12
13 return false
14}

Similar problems

Contains Duplicate

Contains Duplicate III

Comments

Loading comments...

Tags

leetcode

array

hash table

Next Post

LeetCode: Intersection of Two Arrays

Sep 3, 2021

Set intersection

Previous Post

LeetCode: Summary Ranges

Aug 31, 2021

Straight forward checking

HoningJS

Search Posts