Check Duplicates
The problem “Checking for Duplicates” involves identifying if an array A
contains any duplicate elements. This problem can be seen as a special case of checking for a common element between two arrays, but here both arrays are the same. Various approaches can solve this, such as sorting the array first, using a hash set, or a brute-force comparison.
Here’s a table illustrating the value of ( i ) and ( j ) for an array ( A = [2, 1, 3, 1] ) which has one duplicate element (1). The table goes through each combination of ( i ) and ( j ).
Step No | ( i ) Value | ( j ) Value | ( A[i] ) | ( A[j] ) | ( A[i] = A[j] ) |
---|---|---|---|---|---|
1 | 0 | 1 | 2 | 1 | No |
2 | 0 | 2 | 2 | 3 | No |
3 | 0 | 3 | 2 | 1 | No |
4 | 1 | 2 | 1 | 3 | No |
5 | 1 | 3 | 1 | 1 | Yes |
The algorithm would terminate at Step 5 since it finds ( A[i] = A[j] ) (1 = 1) and return true
, indicating that there’s at least one duplicate element in the array.
Here’s a table showing all steps for the array ( A = [2, 1, 3, 1] ) without the check, as if we are printing each step instead of returning boolean values.
Step No | ( i ) Value | ( j ) Value | ( A[i] ) | ( A[j] ) |
---|---|---|---|---|
1 | 0 | 1 | 2 | 1 |
2 | 0 | 2 | 2 | 3 |
3 | 0 | 3 | 2 | 1 |
4 | 1 | 2 | 1 | 3 |
5 | 1 | 3 | 1 | 1 |
6 | 2 | 3 | 3 | 1 |
Here, all combinations of ( i ) and ( j ) are visited once. This is a full enumeration of the pairs of indices.
Brute-force - Java
In this approach, two nested loops compare each pair of elements in the array A
.
|
|
Brute-force - C++
|
|
Brute-force - Python
|
|
Hash Set - Java
Using a hash set provides a more efficient solution.
|
|
Hash Set - C++
|
|
Hash Set - Python
|
|
By using a hash set, you eliminate the need for nested loops, and the operation becomes more efficient with a time complexity of O(n).
Key Takeaway
The outer loop index go from 0 to array length - 1. The inner loop index goes from inner i + 1 to array length. Easy to make out of bounds error when using nested loops.