Statement
Solution
Naive approach
The first solution that comes to mind while looking at this problem would be to iterate over all the elements of the nums
array and compare each element with elements to check whether it is repeating. In this way, we will be able to find out if there are repeating duplicate numbers in the array. However, it is an expensive solution in terms of time complexity, since it comes out to be .
This can be improved in terms of time complexity. Let’s try to devise an optimized solution.
Optimized approach using knowing what to track
An efficient approach would be to keep track of numbers while iterating over nums
. This way, we can find out if an element is repeating by just checking its occurrence instead of checking all the rest of the numbers in nums
.
To achieve this, we will be using the hash map data structure records
that is appropriate for problems like this. We iterate over the nums
array, and for each number, we check if it exists in records
or not. If it exists, then it means that the number is being repeated and the given array nums
contains duplicates hence we return TRUE. If it is not the case, we add the current number to the records
and move to the next number.
If all the numbers have been processed and we haven’t encountered any duplicates, we return FALSE, meaning that there is no duplicate in the given nums
array.
Let’s look at the illustration below to better understand the solution.