220. Contains Duplicate III

220. Contains Duplicate III

Description

Difficulty: Hard

Related Topics: Array, Sliding Window, Sorting, Bucket Sort, Ordered Set

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, and

Return true if such pair exists or false otherwise.

Example 1:

1
2
3
4
5
6
7
Input: nums = [1,2,3,1], indexDiff = 3, valueDiff = 0
Output: true
Explanation: We can choose (i, j) = (0, 3).
We satisfy the three conditions:
i != j --> 0 != 3
abs(i - j) <= indexDiff --> abs(0 - 3) <= 3
abs(nums[i] - nums[j]) <= valueDiff --> abs(1 - 1) <= 0

Example 2:

1
2
3
Input: nums = [1,5,9,1,5,9], indexDiff = 2, valueDiff = 3
Output: false
Explanation: After trying all the possible pairs (i, j), we cannot satisfy the three conditions, so we return false.

Constraints:

  • 2 <= nums.length <= 105
  • -109 <= nums[i] <= 109
  • 1 <= indexDiff <= nums.length
  • 0 <= valueDiff <= 109

Hints/Notes

  • sliding window
  • use map’s lower_bound function
  • it’s not comparing max and min of a sub array, so don’t use monotonic queue

Solution

Language: C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int indexDiff, int valueDiff) {
        int left = 0, right = 0;
        map<intint> m;
        while (right < nums.size()) {
            int val = nums[right];
            auto it = m.lower_bound(val);
            if (it != m.end() && abs(it->first - val) <= valueDiff) {
                return true;
            }
            if (it != m.begin()) {
                it--;
                if (abs(it->first - val) <= valueDiff) {
                    return true;
                }
            }
            m[val]++;
            right++;
            if (right - left > indexDiff) {
                m[nums[left]]--;
                if (m[nums[left]] == 0) {
                    m.erase(nums[left]);
                }
                left++;
            }
        }
        return false;
    }
};