Check whether an array has equal values at most k indices apart

Quick Overview

Given an integer array and an integer k, decide whether two different indices hold the same value and sit at most k positions apart. It tests sliding window reasoning, fast membership lookups, and careful handling of the window bounds and off-by-one cases.

Check whether an array has equal values at most k indices apart

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

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`. Otherwise return `False`. ### Function Signature ```python def contains_nearby_duplicate(nums: list[int], k: int) -> bool: ``` ### Rules - Indices are zero-based, and `i` and `j` must be different indices. A single element never pairs with itself. ### Constraints - `1 <= len(nums) <= 10^5` - `-10^9 <= nums[i] <= 10^9` - `0 <= k <= 10^5` ### Examples ```text Input: nums = [1, 2, 3, 1], k = 3 Output: True ``` `nums[0] == nums[3]` and `abs(0 - 3) == 3`, which is at most 3. ```text Input: nums = [1, 0, 1, 1], k = 1 Output: True ``` `nums[2] == nums[3]` and `abs(2 - 3) == 1`, which is at most 1. ```text Input: nums = [1, 2, 3, 1, 2, 3], k = 2 Output: False ``` Each value appears twice, but every pair of equal values is exactly 3 indices apart, which is more than 2.

Overview: Given an integer array and an integer k, decide whether two different indices hold the same value and sit at most k positions apart. It tests sliding window reasoning, fast membership lookups, and careful handling of the window bounds and off-by-one cases.

Nov 24, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

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. Otherwise return False.

Function Signature

def contains_nearby_duplicate(nums: list[int], k: int) -> bool:

Rules

  • Indices are zero-based, and i and j must be different indices. A single element never pairs with itself.

Constraints

  • 1 <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • 0 <= k <= 10^5

Examples

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

nums[0] == nums[3] and abs(0 - 3) == 3, which is at most 3.

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

nums[2] == nums[3] and abs(2 - 3) == 1, which is at most 1.

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

Each value appears twice, but every pair of equal values is exactly 3 indices apart, which is more than 2.