Contains Duplicate II Lab

Easy
0.0% Acceptance

In this lab, you will implement the Contains Duplicate II function. This function receives an integer array nums and an integer k and returns true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k. Otherwise, it returns false. You can use ESM import/export everywhere.

Problem Description

Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.

Examples

Example 1:

Input: nums = [1, 2, 3, 1], k = 3 Output: true

In this example, the integer array nums contains two 1s with indices 0 and 3, meaning abs(0 - 3) = 3. Since 3 is less than or equal to the given integer k, which is also 3, the function returns true.

Example 2:

Input: nums = [1, 0, 1, 1], k = 1 Output: true

In this example, the integer array nums contains three 1s with indices 0, 2, and 3. The function returns true since abs(2 - 3) = 1, which is less than or equal to the given integer k, which is 1.

Example 3:

Input: nums = [1, 2, 3, 1, 2, 3], k = 2 Output: false

In this example, no pair of equal numbers satisfy the condition abs(i - j) <= k. Therefore, the function returns false.

Constraints

  • 1 <= nums.length <= 105
  • -109 <= nums[i] <= 109
  • 0 <= k <= 105

Challenges

  1. Implement the containsNearbyDuplicate function that takes an integer array nums and an integer k as input and returns a boolean as output.
  2. Export the containsNearbyDuplicate function so that it can be imported in the evaluation script.