Problem 103
Contains Nearby Duplicate
Easy · 10 pts · Array, Hash Table, Sliding Window
Problem
You are given an array of N integers and an integer K. Decide whether there are two different indices i and j such that A[i] = A[j] and the indices are at most K apart, that is, |i - j| <= K. While scanning, keep a hash map from each value to the last index where you saw it. When the current value has been seen before and the distance to its last index is at most K, the answer is YES. Then update its last index.
Input
First line: integers N and K. Second line: N space-separated integers.
Output
Print YES or NO.
Constraints
1 <= N <= 100000; 0 <= K <= 100000; -1000000000 <= A[i] <= 1000000000
Example input
4 3 1 2 3 1
Example output
YES
Explanation
In 1 2 3 1 with K = 3, the two 1's are at indices 0 and 3, which are 3 - 0 = 3 apart. That is within K = 3, so the answer is YES.