Contains Duplicate III LeetCode Solution | Easy Approach

Minimum Cost to Merge Stones
Share:

Contains Duplicate III Given an integer array nums and two integers k and t, return true if there are two distinct indices i and j in the array such that abs(nums[i] - nums[j]) <= t and abs(i - j) <= k.

Example 1:

Input: nums = [1,2,3,1], k = 3, t = 0
Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1, t = 2
Output: true

Example 3:

Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false

Constraints:

  • 1 <= nums.length <= 2 * 104
  • -231 <= nums[i] <= 231 - 1
  • 0 <= k <= 104
  • 0 <= t <= 231 - 1

Contains Duplicate III Solutions

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

C++

class Solution {
 public:
  bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
    set<long> window;

    for (int i = 0; i < nums.size(); ++i) {
      const auto it = window.lower_bound(static_cast<long>(nums[i]) - t);
      if (it != cend(window) && *it - nums[i] <= t)
        return true;
      window.insert(nums[i]);
      if (i >= k)
        window.erase(nums[i - k]);
    }

    return false;
  }
};

Java

 class Solution {
  public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
    TreeSet<Long> set = new TreeSet<>();

    for (int i = 0; i < nums.length; ++i) {
      final long num = (long) nums[i];
      final Long ceiling = set.ceiling(num); // the smallest num >= nums[i]
      if (ceiling != null && ceiling - num <= t)
        return true;
      final Long floor = set.floor(num); // the largest num <= nums[i]
      if (floor != null && num - floor <= t)
        return true;
      set.add(num);
      if (i >= k)
        set.remove((long) nums[i - k]);
    }

    return false;
  }
}

Python


class Solution:
  def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
    if not nums or k <= 0 or t < 0:
      return False

    mini = min(nums)
    diff = t + 1
    bucket = {}

    def getKey(num: int) -> int:
      return (num - mini) // diff

    for i, num in enumerate(nums):
      key = getKey(num)
      if key in bucket:  # current bucket
        return True
      # left adjacent bucket
      if key - 1 in bucket and num - bucket[key - 1] < diff:
        return True
      # right adjacent bucket
      if key + 1 in bucket and bucket[key + 1] - num < diff:
        return True
      bucket[key] = num
      if i >= k:
        del bucket[getKey(nums[i - k])]

    return False

Watch Tutorial

Checkout more Solutions here

Leave a Comment

Your email address will not be published. Required fields are marked *

x