Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Arrays and hashing

A repeated value within k positions

Easy · Target 10 minutes · Arrays and hashing· Type asked at

You're given an integer array nums and an integer k ≥ 0. Return true if you can find two different indices i and j with nums[i] == nums[j] and |i − j| ≤ k, and false if you can't.

Examples

InputOutputWhy
nums = [1, 2, 3, 1], k = 3trueThere's a 1 at 0 and another at 3, so they're 3 apart.
nums = [1, 0, 1, 1], k = 1trueThe 1s at 2 and 3 are next to each other.
nums = [1, 2, 3, 1, 2, 3], k = 2falseEach of the repeats is 3 apart, and that's too far.

Constraints

  • 1 ≤ n ≤ 10⁵
  • −10⁹ ≤ nums[i] ≤ 10⁹
  • 0 ≤ k ≤ 10⁵

Hints

Hint 1

Of all the earlier copies of nums[j], you only ever need to look at one of them. Which one is it, and why can you ignore the others?

Hint 2

Keep a map from each value to the last index where you've seen it.

Hint 3

At index j, look up nums[j]. If you last saw it at i and j − i ≤ k, you're done and can return true. If not, write j over its old entry and move on.

Where people lose marks

  • Keeping the first index of a value in place of the last. Take a value we see at 0, at 10 and again at 12, with k = 3: if we kept 0 we would say no, and the right answer is yes.
  • Putting the value into the map before we look it up, so that every element finds itself at a distance of 0.
  • Testing j − i < k where the problem says ≤ k. One of the examples has a pair that is exactly k apart, to catch this.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.