LeetCode – Contains Duplicate III (Java)

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.

Java Solution 1 - Simple

This solution simple. Its time complexity is O(nlog(k)).

public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        return false;
    TreeSet<Long> set = new TreeSet<Long>();
    for(int i=0; i<nums.length; i++){
        long curr = (long) nums[i];
        long leftBoundary = (long) curr-t;
        long rightBoundary = (long) curr+t+1; //right boundary is exclusive, so +1
        SortedSet<Long> sub = set.subSet(leftBoundary, rightBoundary);
            return true;
        if(i>=k){ // or if(set.size()>=k+1)
    return false;

Java Solution 2 - Deprecated

The floor(x) method returns the greatest value that is less than x. The ceiling(x) methods returns the least value that is greater than x. The following is an example.

public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
	if (k < 1 || t < 0)
		return false;
	TreeSet<Integer> set = new TreeSet<Integer>();
	for (int i = 0; i < nums.length; i++) {
		int c = nums[i];
		if ((set.floor(c) != null && c <= set.floor(c) + t)
		|| (set.ceiling(c) != null && c >= set.ceiling(c) -t))
			return true;
		if (i >= k)
			set.remove(nums[i - k]);
	return false;
Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";

  1. Jingwei Yang on 2015-7-5

    I admire your excellent solution and posts.
    But I believe there is a possible pitfall for your first solution.

    The possible problematic snippet is:
    if (i >= k)
    set.remove(nums[i – k]);
    This would wrongly delete the nums[i], if nums[i] and nums[i – k] have the same value.
    Considering following case:
    nums = [1, 50, 70, 90, 110, 1, 2]
    k = 5
    t = 1
    Using the above logic, when we reach i = 5.
    set. add (5)
    Thus the return for this input is false. Actually it should be true. Cause num[5] = 1, num[6] = 2 meet the requirement.
    The possible fix could be:
    if (i >= k)
    set.remove(nums[i – k]);
    set.add((long) nums[j]);

  2. coder on 2015-7-30

    In that case, ‘true’ must be returned before the snippet.

  3. Jason on 2015-8-23

    In the first case, Could overflow happend?

  4. Ben on 2015-11-8

    yes, it can happen.
    try [max-1,max],1,max

Leave a comment