v9.1.1
Menu

Contains Duplicate II

easyPROHash Maps & CountingLinkedIn DSA

Given an array and integer k, return True if there are two distinct indices i and j such that nums[i] == nums[j] and abs(i - j) <= k.

Example

Input
1,2,3,1
3
Output
True
Reasoning
  • The inputs are the list nums = [1,2,3,1][1, 2, 3, 1] (positions 00 to 33) and the window size k = 33, the largest gap between two positions that still counts as "nearby".
  • A qualifying pair needs two different positions i≠ji \neq j holding the same value, with ∣i−j∣≤k|i - j| \le k. Equal values far apart do not count.
  • In the sample, the values 22 and 33 each appear once, so they can never form a pair. The only repeated value is 11, at positions 00 and 33.
  • Their gap is ∣0−3∣=3|0 - 3| = 3, and 3≤33 \le 3, so the condition holds and the answer is True.
  • Notice how tight this is: with k=2k = 2 the same list gives False, because the two 11s sit exactly 33 apart. Also, k=0k = 0 can never succeed, since the two positions must be distinct.

Constraints

  • 1 <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • 0 <= k <= 10^5

Learn this in

More from LinkedIn DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.