How do you remove duplicates from a sorted array in place?
LeetCode Patterns Flashcards: Two Pointers, Sorted Arrays, Pair Finding, Palindromes
Аудио-карточка · 0:28Nortren·
How do you remove duplicates from a sorted array in place?
0:28
Use a slow pointer to track where the next unique element should be placed and a fast pointer to scan through the array. Start both at the beginning. Move the fast pointer forward. When the fast pointer finds a value different from the element at the slow pointer, increment the slow pointer and copy the fast pointer's value there. After the fast pointer reaches the end, the slow pointer plus one gives the count of unique elements, and the array up to that point contains only unique values. This runs in O of n time and O of one space, modifying the array in place without extra storage.
neetcode.io