Contains Duplicate
Problem Statement
Given an integer array nums
, return true
if any value appears at least twice in the array, and return false
if every element is distinct.
Example: [1,2,3,1]
returns true
as 1
appears more than once
Solutions
1. Brute-force
Metric | Complexity |
---|---|
Time | \( O(N^2) \) |
Space | \( O(1) \) … no extra space |
2. Sorting
When we sort the array, the similar elements would get placed close to each other
C++ code
Time Complexity: \( = O(N \cdot logN) + O(N) = O(N \cdot logN) \)
Metric | Complexity |
---|---|
Time | \( O(N \cdot logN ) \) |
Space | \( O(1) \) … no extra space |
3. Hashing
By using some space for the set, we can quickly check if an element was previouly added to it
C++ code
Metric | Complexity |
---|---|
Time | \( O(N) \) … on avg. |
Space | \( O(N) \) … worst-case, when all are unique |
Above time complexity is for unordered_set
in C++. However, if you use set
, the insertion and find operations would take O(logN)
time in worst-case. So, the final complexity would be O(N*logN)