Contains Duplicate III

You are given an integer array `nums` and two integers `indexDiff` and `valueDiff`. Find a pair of indices `(i, j)` such that: - `i != j`, - `abs(i - j) <= indexDiff`, - `abs(nums[i] - nums[j]) <= valueDiff`. Return `true` if such a pair exists, otherwise return `false`.

30:00

Contains Duplicate III
hard
Free written solution
Topics
Companies

You are given an integer array nums and two integers indexDiff and valueDiff.

Find a pair of indices (i, j) such that:

  • i != j,
  • abs(i - j) <= indexDiff,
  • abs(nums[i] - nums[j]) <= valueDiff.

Return true if such a pair exists, otherwise return false.

Example 1:
Input: {"nums":[1,2,3,1],"indexDiff":3,"valueDiff":0}
Output: true
Constraints:
  • 2≤nums.length≤1052 \leq \text{nums.length} \leq 10^5

  • −109≤nums[i]≤109-10^9 \leq \text{nums}[i] \leq 10^9

  • 1≤indexDiff≤nums.length1 \leq \text{indexDiff} \leq \text{nums.length}

  • 0≤valueDiff≤1090 \leq \text{valueDiff} \leq 10^9

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,2,3,1],"indexDiff":3,"valueDiff":0}

Cut the number line into buckets of width valueDiff + 1 = 1. Two values in the same bucket are always within 0, so each bucket can hold at most one value before we have an answer.

nums, window = last 3 indexes

1

0

2

1

3

2

1

3

buckets of width 1 (valueDiff + 1)

no buckets yet

valueDiff = 0

Variables
VariableValue
width1
DepthFunction Call
Stack empty
0/10