Hey, π₯π
can you find the unique number in a list of duplicates? It's an interesting interview question which has many solutions.
Let's have a closer look:
Given: a list or an array having all elements twice except one element, like this:
A = [2, 8, 1, 8, 2]
Expected answer: 1 (i.e. figure out the unique element)
Problem Constraints:
- 1 <= length of A <= 3 * 10^4
- -3 * 10^4 <= A[i] <= 3 * 10^4
-----------------------------------------------------------------------------------------------------------------------------
Method 1: Brute force approach
- For this approach:
Time Complexity: O(n^2) // two for loops (nested)
Space Complexity: O(1) // no extra space used
-----------------------------------------------------------------------------------------------------------------------------
Method 2: Hashing (to avoid O(n) time for searching)
- For this approach:
Time Complexity: O(n) // for iteration through the list/array
Space Complexity: O(n) // extra linear space used
-----------------------------------------------------------------------------------------------------------------------------
Method 3: Bit Manipulation ⭐
Hint: properties of XOR operation (⊕) :
- a ⊕ 0 = a
- a ⊕ a = 0
- a ⊕ b ⊕ a = (a ⊕ a) ⊕ b = 0 ⊕ b = b
[a, b being Boolean variables or bits: 1 or 0]
- Crux: XOR-ing a list of numbers removes duplicates since a ⊕ a = 0, leaving behind the unique number, because a ⊕ 0 = a.
Hence, solution:
Time Complexity: O(n) // for iteration through the list/array
Space Complexity: O(1) // no extra space used
-----------------------------------------------------------------------------------------------------------------------------
That's it! Explore, practice and move on...π
No comments:
Post a Comment