#220

Contains Duplicate III

Hard
ArraySliding WindowSortingBucket SortOrdered SetHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log k)
Space
O(1)
O(k)
💡

Intuition

Time O(n log k)Space O(k)

The optimal solution uses a sliding window approach combined with a balanced tree structure to maintain a window of k elements. This allows us to efficiently check for the required conditions without re-sorting.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a set to store the elements in the current sliding window of size indexDiff.
  2. 2Step 2: Iterate through the array, adding each element to the set.
  3. 3Step 3: For each new element, check if there exists an element in the set that meets the valueDiff condition using binary search.
  4. 4Step 4: If the size of the set exceeds indexDiff, remove the oldest element from the set.
  5. 5Step 5: If any valid pair is found during the checks, return true. If the loop completes without finding a pair, return false.
solution.py13 lines
1from sortedcontainers import SortedList
2
3def containsNearbyAlmostDuplicate(nums, indexDiff, valueDiff):
4    sorted_list = SortedList()
5    for i in range(len(nums)):
6        if i > indexDiff:
7            sorted_list.remove(nums[i - indexDiff - 1])
8        pos1 = sorted_list.bisect_left(nums[i] - valueDiff)
9        pos2 = sorted_list.bisect_right(nums[i] + valueDiff)
10        if pos1 != pos2:
11            return True
12        sorted_list.add(nums[i])
13    return False

Complexity note: This complexity is due to maintaining a sorted set of size k (indexDiff), allowing us to perform efficient insertions and lookups.

  • 1Using a sliding window allows us to limit the number of comparisons and efficiently check conditions.
  • 2Maintaining a sorted structure helps in quickly finding if any number within the required range exists.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.