InferenceAI

Enter at least two characters to search.

Start free

Duplicate Within Distance

easyArrays & Hashing15 min10 XP

Return True if there are two different indices ii and jj with nums[i] == nums[j] and ∣i−j∣≤k|i - j| \le k. Otherwise return False.

Requirements

  • Aim for O(n)O(n) time.

Constraints

  • 0≤k≤1050 \le k \le 10^5, 0≤n≤1050 \le n \le 10^5

Examples

EXAMPLE WALKTHROUGHrepeat exactly k apart

A guided view of the published example, not a trace of your code.

INPUT[[1,2,3,1],3]
TASKduplicate_within_distance()
EXPECTED OUTPUTtrue

Start with the input values shown in this example.

Example 1 of 3

Input: nums = [1,2,3,1], k = 3

Output: true

Explanation: repeat exactly k apart

Input: nums = [1,0,1,1], k = 1

Output: true

Explanation: adjacent repeat

Input: nums = [1,2,3,1,2,3], k = 2

Output: false

Explanation: repeats too far apart

Hint 1

Remember the most recent index of each value.

Hint 2

A sliding set of the last k values also works.

Topics

DSAArrays & HashingPython