Finding dups
Given an array of integers nums
containing n + 1
integers where each integer is in the range [1, n]
inclusive.
There is only one repeated number in nums
, return this repeated number.
Brute Force: We consider each number from 1 to n, and traverse over the whole nums array to check if the current number occurs twice in nums.
Honorable mentions: Gauss Formula and Tortoise and Hare technique
When encountering problems that involving finding the duplicates of an array of some sort, one of the most useful and elegant techniques for a O(1) Space Complexity and O(N) time is to use the numbers in the array as indices to parcour the array and to subsequently set them to negative thereby indicating that they've been visited before hence that number being a duplicate.
Conversely, as seen in the below code, if the identified number is not negative, this signify that it has not been visited before due to the number being missing. Reminder to add 1 as the method to arrive to the element requires the index to be substracted by 1.
Last updated
Was this helpful?