How do you detect duplicates in an array efficiently?
LeetCode Patterns Flashcards: Arrays and Hashing, Frequency Maps, Duplicates
Аудио-карточка · 0:30Nortren·
How do you detect duplicates in an array efficiently?
0:30
Insert elements into a hash set as you iterate through the array. Before each insertion, check if the element already exists in the set. If it does, you found a duplicate. This runs in O of n time and O of n space. For the variant "contains duplicate within k distance," use a sliding window hash set of size k, removing elements that fall outside the window. If the problem forbids extra space, sorting the array first in O of n log n time and then checking adjacent elements works. Choose the approach based on constraints: hash set for speed, sorting for space efficiency.
neetcode.io