nums
.true
, otherwise we return false
.nums
.true
immediately.false
.
The brute force approach is inefficient because it requires comparing every pair of elements in the array, leading to a time complexity of O(n^2)
, where n
is the length of the array. This becomes slow for larger arrays because the number of comparisons grows quadratically as the size of the array increases.
set
to track the elements we've already seen.true
immediately.O(1)
, making the time complexity of the solution O(n)
where n
is the length of the array.O(n)
as we might need to store up to n
elements in the worst case.
The “Contains Duplicate” problem is a foundational algorithmic task that asks whether any value appears more than once in a given integer array nums
.
If any element appears at least twice, the function should return true
; if every element is distinct, it should return false
.
Example:
[1, 2, 3, 1]
→ Output: true
(1 appears twice)[1, 2, 3, 4]
→ Output: false
(no duplicates)This problem is commonly asked in interviews and introduces you to basic data structures like hash sets. It sharpens your ability to trade time for space and shows the benefit of using efficient data lookups to avoid nested iteration. It's also highly relevant in real-world scenarios like checking for duplicate entries in data, logs, or transactions.
The brute-force solution involves comparing each element with every other element that comes after it.
If a match is found, we return true
. If no matches are found after all comparisons, we return false
.
While this approach is simple and works correctly, it requires O(n²)
time due to the nested loop, which becomes impractical for large arrays.
The optimal solution leverages a hash set to track the elements we've already seen.
Sets in most programming languages allow O(1)
average time complexity for insertions and membership checks.
Here's the process:
seen
.num
in the input array.num
is already in seen
, return true
immediately (duplicate found).num
to seen
.false
.
Input: [3, 1, 4, 2, 1]
seen = {}
seen
→ add → {3}
seen
→ add → {1, 3}
{1, 3, 4}
{1, 2, 3, 4}
seen
→ return true
Time Complexity: O(n), where n
is the number of elements in the array. Each lookup and insertion into the set is done in constant time.
Space Complexity: O(n) in the worst case, to store up to n
distinct elements in the set.
false
, since there are no duplicates.false
, as there's nothing to compare.true
false
The “Contains Duplicate” problem is an elegant example of how a simple data structure like a set can drastically improve performance over brute-force approaches. It reinforces key principles in algorithm design: using hash-based lookups to avoid redundant work and identifying opportunities to optimize nested iterations.