Single Number 3 LeetCode Solution - The Coding Shala
Home >> LeetCode >> Single Number 3
In this post, we will learn how to solve LeetCode's Single Number 3 problem and will implement its solution in Java.
Single Number 3 Problem
Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order.
Input: nums = [1,2,1,3,2,5]
Explanation: [5, 3] is also a valid answer.
Input: nums = [-1,0]
Input: nums = [0,1]
Practice this problem on LeetCode.
LeetCode - Single Number 3 Java Solution
Using HashMap [ Extra Space].
Using Bit Manipulation.
We will follow the below steps:
- step 1: XOR all the numbers, the result will be res1 ^ res2.
- step 2: Now our result contains both single numbers xor if a bit is zero in xor that means both the bit in res1 and res 2 is the same so we can't determine with that. We need to find the 1 bit index. Traverse all the 32-bit indexes of the XOR result, once we find there exists 1 bit on the index, break the loop.
- Step 3: Now we have an index that has 1 bit so one of our numbers has 1 bit at that index so we will traverse all the numbers in the input array, if we find a number with a bit index that is not 0 then we can use res1 XOR current num to iteratively fill out an effective bit in res1.For example res1 ^ n1 ^ n1 = res1. [n1 appears twice]
- Step 4: we have res1 so by doing res1 ^ allnNumberoXor we will get res2.
Other Posts You May Like
- LeetCode - Single Number
- LeetCode - Single Number 2
- LeetCode - Number of 1 bit
- LeetCode - To Lower Case
- LeetCode - Word Subsets