Problem
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.
OR
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.
Examples
Example 1:
| |
Example 2:
| |
Solution
Method 1 - Using TreeSet and Sliding Window
To solve the problem, we can use a sliding window approach and a data structure that allows efficient insertion, deletion, and lookup. A TreeSet provides these capabilities with logarithmic time complexity for each operation, making it a good choice for this problem.
Approach
- Use a
TreeSetto maintain a sliding window ofindexDifforksize. - For each element in
nums:- Use
TreeSet.floor()andTreeSet.ceiling()to find the nearest elements within thevalueDiffort. - If any such element is found, return
true. - Maintain the sliding window by adding the current element to the set and removing the element that is
indexDifforkpositions before the current index.
- Use
Lets see what floor and ceiling mean.
| |
So, if TreeSet has following elements:
| |
Then, here are floor and ceiling of 3:
| |
Code
| |
Complexity
- ⏰ Time complexity:
O(n log k)wherenis the length of the array andkisindexDiff. Because, we check each numbers floors and ceils, then add it to set, which takeslog k, as we only storekelements in Treeset, and we do it for n elements, henceO(n log k) - 🧺 Space complexity:
O(k)