Skip to content
This repository has been archived by the owner on Aug 14, 2024. It is now read-only.

Latest commit

 

History

History
31 lines (23 loc) · 914 Bytes

219.md

File metadata and controls

31 lines (23 loc) · 914 Bytes

219. Contains Duplicates

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.

Thinking Process

  1. Use a hashmap to store where an element appears last time
  2. Whenever we encounter an element that's in the map, compare the difference between the two indices and k

Code

public 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;
    }
}

Complexity

  1. Time complexity is O(n)
  2. Space complexity is O(n)