clueless coding // TODO: be smarter

LeetCode 219. Contains Duplicate II: C++ Solution



Problem Statement


Given an array of integers and an integer k, design an algorithm that determines 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.

Function Signature (C++):
  bool containsNearbyDuplicate(vector<int>& nums, int k)

Inputs:
  nums = [1, 2, 3, 4, 1]
  k = 4

Outputs:
true

Inputs:
  nums = [1, 2, 3, 1, 4]
  k = 4

Outputs:
false



TL;DR Code Solution


bool containsNearbyDuplicate(vector<int>& nums, int k) {

    unordered_map<int, int> map;

    for (int i = 0; i < nums.size(); i++) {

        if (map.find(nums[i]) != map.end()) {
            if (i - map[nums[i]] <= k) {
                return true;
            }
        }
        map[nums[i]] = i;

    }

    return false;

}