📘
Contains Duplicate II
Given an array and integer k, return True if there are two distinct indices i and j such that nums[i] == nums[j] and abs(i - j) <= k.
Example:
Input:
1,2,3,1 3
Output:
True
Reasoning:
- The input array is
[1, 2, 3, 1]and the integerkis 3. - We iterate through the array to find duplicate elements within a distance of k indices.
- At index 0, the value is 1, and at index 3, the value is also 1, with an index difference of abs(0−3)=3, which satisfies the condition abs(i−j)≤k.
- Since a duplicate is found within the specified distance, the function returns
True.
Constraints:
- 1 <= len(nums) <= 10^5
- -10^9 <= nums[i] <= 10^9
- 0 <= k <= 10^5
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.