TRT
Sign in
hardAdvancedLeetCode#ordered set over a sliding window#buckets

Contains duplicate III

Find two values close in position and in value, with a ceiling query on an ordered window.

The Runtime Theory Team1 min read
Taught inChoosing an ordered structurePro — members onlySorted arrays, heaps, balanced trees, skip lists and B-trees all keep data in order, with very different costs. The right choice follows from which operations you need, how often the data changes, and what your language provides.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

innums = [1, 2, 3, 1], indexDiff = 3, valueDiff = 0

outtrue

innums = [1, 5, 9, 1, 5, 9], indexDiff = 2, valueDiff = 3

outfalse

innums = [8, 1, 5, 9, 4], indexDiff = 2, valueDiff = 1

outtrue

Return true if there are indexes i ≠ j with |i − j| ≤ indexDiff and |nums[i] − nums[j]| ≤ valueDiff.

Before you code

Keep the last indexDiff values in some structure. For a new value x, which single question about that structure decides whether a close value exists?

Hints

  1. Keep the window's values in an ordered set, such as SortedList in Python or TreeSet in Java.
  2. For each x, find the smallest value at least x − valueDiff. If it exists and is at most x + valueDiff, return true.
  3. Add x, and remove the value that falls out of the window. Total O(n log k).
  4. Afterwards, try the O(n) alternative: buckets of width valueDiff + 1 in a hash map, checking the same and neighboring buckets.

Production & complexity notes

When solving Contains duplicate III on LeetCode (hard), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Choosing an ordered structure to reinforce the underlying pattern.

What it practices

Ordered-set queries over a sliding window, from Choosing an ordered structure.

Not started

Sign in to save your learning progress.

Sign in to save