Similar Problems
Similar Problems not available
Elimination Game - Leetcode Solution
Companies:
LeetCode: Elimination Game Leetcode Solution
Difficulty: Medium
Topics: math
Problem:
Given an integer array nums, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and using only constant extra space.
Solution:
Approach 1: Hashset
One of the simplest solutions to this problem is to use a Hashset to store the elements of the given array nums. We can iterate through the array and for every element, we check if it exists in the Hashset. If it doesn't exist, we add it to the Hashset. If it does exist, we remove it from the Hashset. By the end of the iteration, the Hashset will only contain the element that appears once in the original array.
Time complexity: O(n). We iterate through the entire array once. Space complexity: O(n). We store at most n elements in the Hashset.
Approach 2: Bit manipulation
Another approach to this problem is to use bit manipulation. The idea is to XOR all the elements in the array. Since every element appears twice except for one, the XOR of all elements will cancel out the duplicates, leaving only the element that appears once.
Time complexity: O(n). We iterate through the entire array once. Space complexity: O(1). We only need constant extra space to store the result.
Code:
Approach 1: Hashset
class Solution { public int singleNumber(int[] nums) { HashSet<Integer> set = new HashSet<>(); for (int num : nums) { if (set.contains(num)) { set.remove(num); } else { set.add(num); } } return set.iterator().next(); } }
Approach 2: Bit manipulation
class Solution { public int singleNumber(int[] nums) { int ans = 0; for (int num : nums) { ans ^= num; } return ans; } }
Elimination Game Solution Code
1