KatInterview

220. Contains Duplicate III

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to determine if there exist two distinct indices i and j in an array nums that satisfy two conditions simultaneously:

Solution

Contains Duplicate III in Python

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

        # Bucket size. Add 1 to handle valueDiff=0 case and ensure numbers
        # in the same bucket have a difference of at most valueDiff.
        bucket_size = valueDiff + 1
        buckets = {}

        for i, num in enumerate(nums):
            # In Python, `//` operator performs floor division, which works correctly
            # for both positive and negative numbers.
            bucket_id = num // bucket_size

            # Check if the current bucket contains a nearby number.
            if bucket_id in buckets:
                return True

            # Check the left adjacent bucket.
            if (bucket_id - 1) in buckets and abs(num - buckets[bucket_id - 1]) <= valueDiff:
                return True

            # Check the right adjacent bucket.
            if (bucket_id + 1) in buckets and abs(num - buckets[bucket_id + 1]) <= valueDiff:
                return True

            # Add current element to its bucket.
            buckets[bucket_id] = num

            # Remove the element that falls out of the window of size indexDiff.
            if i >= indexDiff:
                old_num = nums[i - indexDiff]
                old_bucket_id = old_num // bucket_size
                # We must check if the bucket to be removed contains the correct old number,
                # as it might have been updated by a more recent number.
                if old_bucket_id in buckets and buckets[old_bucket_id] == old_num:
                    del buckets[old_bucket_id]

        return False

Contains Duplicate III in Java

class Solution {
    public boolean containsNearbyAlmostDuplicate(int[] nums, int indexDiff, int valueDiff) {
        if (indexDiff <= 0 || valueDiff < 0) {
            return false;
        }

        // The width of a bucket. Using long to prevent overflow.
        long width = (long) valueDiff + 1;
        // Map from bucket ID to the number in that bucket.
        Map<Long, Long> buckets = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            long num = (long) nums[i];
            long bucketId = getBucketId(num, width);

            // Check if the current bucket contains a nearby number.
            if (buckets.containsKey(bucketId)) {
                return true;
            }

            // Check the left adjacent bucket.
            if (buckets.containsKey(bucketId - 1) && Math.abs(num - buckets.get(bucketId - 1)) <= valueDiff) {
                return true;
            }

            // Check the right adjacent bucket.
            if (buckets.containsKey(bucketId + 1) && Math.abs(num - buckets.get(bucketId + 1)) <= valueDiff) {
                return true;
            }

            // Add current element to its bucket.
            buckets.put(bucketId, num);

            // Remove the element that falls out of the window of size indexDiff.
            if (i >= indexDiff) {
                long oldNum = (long) nums[i - indexDiff];
                long oldBucketId = getBucketId(oldNum, width);
                // Important: only remove the bucket if the number stored is the one we expect.
                // This handles cases where a bucket might have been updated by a more recent number.
                if (buckets.containsKey(oldBucketId) && buckets.get(oldBucketId) == oldNum) {
                    buckets.remove(oldBucketId);
                }
            }
        }

        return false;
    }

    // Helper function to get bucket ID.
    // Handles negative numbers correctly.
    private long getBucketId(long num, long width) {
        // In Java, integer division truncates towards zero.
        // We want floor division.
        if (num >= 0) {
            return num / width;
        } else {
            // For negative numbers, `(num + 1) / width - 1` simulates floor division.
            // e.g., num=-1, width=4. bucket should be -1. (-1+1)/4 - 1 = -1.
            // e.g., num=-4, width=4. bucket should be -1. (-4+1)/4 - 1 = -1.
            // e.g., num=-5, width=4. bucket should be -2. (-5+1)/4 - 1 = -2.
            return (num + 1) / width - 1;
        }
    }
}

Contains Duplicate III in C++

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int indexDiff, int valueDiff) {
        int n = nums.size();
        if (n < 2 || indexDiff <= 0 || valueDiff < 0) {
            return false;
        }

        // Use long long for bucket width to avoid overflow if valueDiff is INT_MAX
        long long width = (long long)valueDiff + 1;
        // Buckets map: bucket_id -> value
        unordered_map<long long, long long> buckets;

        for (int i = 0; i < n; ++i) {
            long long num = nums[i];
            long long bucketId = getBucketId(num, width);

            // Check if the current bucket contains a nearby number
            if (buckets.count(bucketId)) {
                return true;
            }

            // Check the left adjacent bucket
            if (buckets.count(bucketId - 1) && abs(num - buckets[bucketId - 1]) <= valueDiff) {
                return true;
            }

            // Check the right adjacent bucket
            if (buckets.count(bucketId + 1) && abs(num - buckets[bucketId + 1]) <= valueDiff) {
                return true;
            }

            // Add current element to its bucket
            buckets[bucketId] = num;

            // Remove the element that falls out of the window of size indexDiff
            if (i >= indexDiff) {
                long long oldNum = nums[i - indexDiff];
                long long oldBucketId = getBucketId(oldNum, width);
                // Check if the element to be removed is the one in the bucket
                // This check is important because a bucket might have been updated by a more recent number
                if (buckets.count(oldBucketId) && buckets[oldBucketId] == oldNum) {
                    buckets.erase(oldBucketId);
                }
            }
        }

        return false;
    }

private:
    // Helper function to get bucket ID
    long long getBucketId(long long num, long long width) {
        // For non-negative numbers, it's simple division.
        // For negative numbers, we need to handle it carefully to ensure correct floor division behavior.
        // C++ integer division truncates towards zero.
        if (num >= 0) {
            return num / width;
        } else {
            // e.g., num=-1, width=4. bucket should be -1. (-1+1)/4 - 1 = -1.
            // e.g., num=-4, width=4. bucket should be -1. (-4+1)/4 - 1 = -1.
            // e.g., num=-5, width=4. bucket should be -2. (-5+1)/4 - 1 = -2.
            return (num + 1) / width - 1;
        }
    }
};

Contains Duplicate III in TypeScript

function containsNearbyAlmostDuplicate(nums: number[], indexDiff: number, valueDiff: number): boolean {
    if (indexDiff <= 0 || valueDiff < 0) {
        return false;
    }

    const bucketSize = valueDiff + 1;
    const buckets: Map<number, number> = new Map();

    for (let i = 0; i < nums.length; i++) {
        const num = nums[i];
        // Math.floor handles both positive and negative numbers correctly for bucketing.
        const bucketId = Math.floor(num / bucketSize);

        // Check if the current bucket contains a nearby number.
        if (buckets.has(bucketId)) {
            return true;
        }

        // Check the left adjacent bucket.
        if (buckets.has(bucketId - 1) && Math.abs(num - buckets.get(bucketId - 1)!) <= valueDiff) {
            return true;
        }

        // Check the right adjacent bucket.
        if (buckets.has(bucketId + 1) && Math.abs(num - buckets.get(bucketId + 1)!) <= valueDiff) {
            return true;
        }

        // Add current element to its bucket.
        buckets.set(bucketId, num);

        // Remove the element that falls out of the window of size indexDiff.
        if (i >= indexDiff) {
            const oldNum = nums[i - indexDiff];
            const oldBucketId = Math.floor(oldNum / bucketSize);
            // Check if the bucket to be removed contains the correct old number.
            if (buckets.has(oldBucketId) && buckets.get(oldBucketId) === oldNum) {
                buckets.delete(oldBucketId);
            }
        }
    }

    return false;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.