← Back to index
HardPHP4 min read

Contains Duplicate III

check if there exist two indices with value difference ≤ valueDiff and index difference ≤ indexDiff using sliding window with sorted array.

sliding-windowbinary-searcharrays

Problem link

View on LeetCode

Solutions in this repo

  • PHP../contains-duplicate-3/solution.phpPHP solution

maintain a sliding window of size indexDiff using a sorted array. for each new element, binary search to find insertion position, then check adjacent elements for value difference ≤ valueDiff.

when window exceeds indexDiff, remove the oldest element using binary search. the sorted window allows efficient range queries.

key insight

by keeping the window sorted, we can quickly check if any element within valueDiff exists. binary search gives O(log k) insertion and removal where k is window size.

complexity

O(n log k) time where n is array length and k is indexDiff. O(k) space for the sorted window.