219-contains-duplicate-ii
Question
https://leetcode.com/problems/contains-duplicate-ii/description/
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
Example:
Thought Process
- Brute Force - Check the range of K (TLE)
- Two pointers tracking the start and end points
 - Time complexity O(n min(k, n))
 - Space complexity O(1)
 
 - Hash Table
- Use map to store the number and its index to find the difference at O(1) time, Or Set to keep size of range for comparison
 - Time complexity O(n)
 - Space complexity O(n), and O(min(n. k)) for set
 
 - Separate Class - Sorting
- Create a separate class node to store the value and its index
 - After sorting, we simply check the node's index with its previous element's index is within the range of k
 - Default library arrays sort use merge sort for objects, so it's stable, so we don't need to include the index in the compareTo function
 - Time complexity O(n logn)
 - Space complexity O(n)
 
 
Solution
Brute Force
class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        for (int i = 1 ; i < nums.length; i++) {
            for (int j = Math.max(0, i - k); j < i; j++) {
                if (nums[i] == nums[j]) return true;
            }
        }
        return false;
    }
}
Hash Table
class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) return true;
            map.put(nums[i], i);
        }
        return false;
    }
}
class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (i > k) set.remove(nums[i - k - 1]);
            if (!set.add(nums[i])) return true;
        }
        return false;
    }
}
Separate Node
class Solution {
    private static class Node implements Comparable<Node> {
        private int value, index;
        public Node(int value, int index) {
            this.value = value;
            this.index = index;
        }
        public int compareTo(Node that) {
            return this.value - that.value;
        }
    }
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        int n = nums.length;
        Node[] nodes = new Node[n];
        for (int i = 0; i < n; i++) {
            nodes[i] = new Node(nums[i], i);
        }
        Arrays.sort(nodes);
        for (int i = 1; i < n; i++) {
            if (nodes[i].value == nodes[i - 1].value && nodes[i].index - nodes[i - 1].index <= k) return true;
        }
        return false;
    }
}