220. Contains Duplicate III
HardView on LeetCode
Time: O(n)
Space: O(k)
Problem Overview
Contains Duplicate III (Hard) asks you to solve a structured algorithmic task. This is a common Array / Sorting pattern in coding interviews. Bucket sort with bucket size valueDiff+1; within a sliding window
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Bucket sort with bucket size valueDiff+1; within a sliding window
of indexDiff, check the same and two adjacent buckets for a near-duplicate.
Related patterns: Array, Sorting, Sliding Window
220.cs
C#
// Approach: Bucket sort with bucket size valueDiff+1; within a sliding window
// of indexDiff, check the same and two adjacent buckets for a near-duplicate.
// Time: O(n) Space: O(k)
public class Solution
{
public bool ContainsNearbyAlmostDuplicate(int[] nums, int indexDiff, int valueDiff)
{
if (nums.Length == 0 || indexDiff <= 0 || valueDiff < 0)
return false;
long mn = nums.Min();
long diff = valueDiff + 1; // In case that `valueDiff` equals 0.
// Use long because of corner case int.MaxValue - (-1) will overflow
Dictionary<long, long> bucket = new Dictionary<long, long>();
for (int i = 0; i < nums.Length; ++i)
{
long num = (long)nums[i];
long key = GetKey(nums[i], mn, diff);
if (bucket.ContainsKey(key)) // the current bucket
return true;
if (bucket.ContainsKey(key - 1) && num - bucket[key - 1] < diff) // the left adjacent bucket
return true;
if (bucket.ContainsKey(key + 1) && bucket[key + 1] - num < diff) // the right adjacent bucket
return true;
bucket[key] = num;
if (i >= indexDiff)
bucket.Remove(GetKey(nums[i - indexDiff], mn, diff));
}
return false;
}
private long GetKey(int num, long mn, long diff)
{
return (num - mn) / diff;
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)
- 26. Remove Duplicates from Sorted Array(Easy)
- 27. Remove Element(Easy)