Given an array nums where each integer in nums appears thrice except one. Find out the number that has appeared only once.
Input : nums = [2, 2, 2, 3]
Output : 3
Explanation : The integers 3 has appeared only once.
Input : nums = [1, 0, 3, 0, 1, 1, 3, 3, 10, 0]
Output : 10
Explanation : The integers 10 has appeared only once.
Input : nums = [5, 0, 1, 10, 1, 1, 5, 5, 10, 10]
The brute force way to solve this will be to utilize a frequency counting approach. By keeping track of the frequency of each element in the array, the element that appears only once can be easily identified.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Function to get the single
number in the given array */
int singleNumber(vector<int>& nums){
/* Map to store the elements
and their frequencies */
unordered_map <int, int> mpp;
// Iterate on the array
for(int i=0; i < nums.size(); i++) {
mpp[nums[i]]++; //Update the map
}
//Iterate on the map
for(auto it : mpp) {
// If frequency is 1
if(it.second == 1) {
// Return the element
return it.first;
}
}
/* Return -1, if there is no
number having frequency 1 */
return -1;
}
};
int main() {
vector<int> nums = {2, 2, 2, 3};
/* Creating an instance of
Solution class */
Solution sol;
/* Function call to get the single
number in the given array */
int ans = sol.singleNumber(nums);
cout << "The single number in given array is: " << ans;
return 0;
}
import java.util.HashMap;
class Solution {
/* Function to get the single
number in the given array */
public int singleNumber(int[] nums) {
/* Map to store the elements
and their frequencies */
HashMap<Integer, Integer> mpp = new HashMap<>();
// Iterate on the array
for (int i = 0; i < nums.length; i++) {
mpp.put(nums[i], mpp.getOrDefault(nums[i], 0) + 1); // Update the map
}
// Iterate on the map
for (HashMap.Entry<Integer, Integer> it : mpp.entrySet()) {
// If frequency is 1
if (it.getValue() == 1) {
// Return the element
return it.getKey();
}
}
/* Return -1, if there is no
number having frequency 1 */
return -1;
}
public static void main(String[] args) {
int[] nums = {2, 2, 2, 3};
/* Creating an instance of
Solution class */
Solution sol = new Solution();
/* Function call to get the single
number in the given array */
int ans = sol.singleNumber(nums);
System.out.println("The single number in given array is: " + ans);
}
}
class Solution:
# Function to get the single
# number in the given array
def singleNumber(self, nums):
# Map to store the elements
# and their frequencies
mpp = {}
# Iterate on the array
for num in nums:
mpp[num] = mpp.get(num, 0) + 1 # Update the map
# Iterate on the map
for key, value in mpp.items():
# If frequency is 1
if value == 1:
# Return the element
return key
# Return -1, if there is no
# number having frequency 1
return -1
# Test the function
nums = [2, 2, 2, 3]
# Creating an instance of Solution class
sol = Solution()
# Function call to get the single number in the given array
ans = sol.singleNumber(nums)
print("The single number in given array is:", ans)
class Solution {
/* Function to get the single
number in the given array */
singleNumber(nums) {
/* Map to store the elements
and their frequencies */
let mpp = new Map();
// Iterate on the array
for (let i = 0; i < nums.length; i++) {
mpp.set(nums[i], (mpp.get(nums[i]) || 0) + 1); // Update the map
}
// Iterate on the map
for (let [key, value] of mpp.entries()) {
// If frequency is 1
if (value === 1) {
// Return the element
return key;
}
}
/* Return -1, if there is no
number having frequency 1 */
return -1;
}
}
// Test the function
let nums = [2, 2, 2, 3];
/* Creating an instance of
Solution class */
let sol = new Solution();
/* Function call to get the single
number in the given array */
let ans = sol.singleNumber(nums);
console.log("The single number in given array is: " + ans);
Time Complexity: O(N) (where N is the size of the array) –
Space Complexity: O(N) – Using a hashmap data structure and in the worst-case (when all elements in the array are unique), it will store N key-value pairs.
A better approach would be to use the properties of binary representation and bit manipulation. The idea is to count the bits at each position.
For elements appearing three times, the bit count will be a multiple of three. The unique element's bit will not follow this pattern, using which it could be identified.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Function to get the single
number in the given array */
int singleNumber(vector<int>& nums){
// Variable to store size of array
int n = nums.size();
// Variable to store the ans
int ans = 0;
// Checking every bit position
for(int bitIndex = 0; bitIndex < 32; bitIndex++) {
/* Variable to count number of
set bits in bitIndex position */
int count = 0;
// Traversing all elements
for(int i = 0; i < n; i++) {
/* Counting elements having set
bits at bitIndex position */
if(nums[i] & (1 << bitIndex)) {
count++;
}
}
// Updating bits in answer
if(count % 3 != 0) {
ans |= (1 << bitIndex);
}
}
return ans;
}
};
int main() {
vector<int> nums = {2, 2, 2, 3};
/* Creating an instance of
Solution class */
Solution sol;
/* Function call to get the single
number in the given array */
int ans = sol.singleNumber(nums);
cout << "The single number in given array is: " << ans;
return 0;
}
import java.util.*;
class Solution {
/* Function to get the single
number in the given array */
public int singleNumber(int[] nums) {
// Variable to store size of array
int n = nums.length;
// Variable to store the ans
int ans = 0;
// Checking every bit position
for (int bitIndex = 0; bitIndex < 32; bitIndex++) {
/* Variable to count number of
set bits in bitIndex position */
int count = 0;
// Traversing all elements
for (int i = 0; i < n; i++) {
/* Counting elements having set
bits at bitIndex position */
if ((nums[i] & (1 << bitIndex)) != 0) {
count++;
}
}
// Updating bits in answer
if (count % 3 != 0) {
ans |= (1 << bitIndex);
}
}
return ans;
}
public static void main(String[] args) {
int[] nums = {2, 2, 2, 3};
/* Creating an instance of
Solution class */
Solution sol = new Solution();
/* Function call to get the single
number in the given array */
int ans = sol.singleNumber(nums);
System.out.println("The single number in given array is: " + ans);
}
}
class Solution:
# Function to get the single
# number in the given array
def singleNumber(self, nums):
# Variable to store the ans
ans = 0
# Checking every bit position
for bitIndex in range(32):
# Variable to count number of
# set bits in bitIndex position
count = 0
# Traversing all elements
for num in nums:
# Counting elements having set
# bits at bitIndex position
if num & (1 << bitIndex):
count += 1
# Updating bits in answer
if count % 3 != 0:
ans |= (1 << bitIndex)
# Handling negative numbers
if ans >= 2**31: # If the sign bit is set
ans -= 2**32
return ans
if __name__ == "__main__":
nums = [2, 2, 2, 3]
# Creating an instance of
# Solution class
sol = Solution()
# Function call to get the single
# number in the given array
ans = sol.singleNumber(nums)
print("The single number in the given array is:", ans)
class Solution {
/* Function to get the single
number in the given array */
singleNumber(nums) {
// Variable to store the ans
let ans = 0;
// Checking every bit position
for (let bitIndex = 0; bitIndex < 32; bitIndex++) {
/* Variable to count number of
set bits in bitIndex position */
let count = 0;
// Traversing all elements
for (let i = 0; i < nums.length; i++) {
/* Counting elements having set
bits at bitIndex position */
if (nums[i] & (1 << bitIndex)) {
count++;
}
}
// Updating bits in answer
if (count % 3 != 0) {
ans |= (1 << bitIndex);
}
}
return ans;
}
}
const nums = [2, 2, 2, 3];
/* Creating an instance of
Solution class */
const sol = new Solution();
/* Function call to get the single
number in the given array */
const ans = sol.singleNumber(nums);
console.log("The single number in given array is:", ans);
Time Complexity: O(32*N) – For every 32-bit position, all the elements of the array are traversed.
Space Complexity: O(1) – Using a couple of variables i.e., constant space.
The most optimal way to solve this problem is by grouping (forming buckets) all the identical elements which can be done by sorting the array.
Now, the question of finding the single number will boil down to check for the number that doesn't follow the pattern of appearing three times consecutively.
What if there is no single number found in the array during traversal?
The single number must be the last element in the array because the array is sorted, and all other elements would have been grouped by threes.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Function to get the single
number in the given array */
int singleNumber(vector<int>& nums) {
// Variable to store size of array
int n = nums.size();
// Sorting the array
sort(nums.begin(), nums.end());
// Traversing the array
for (int i = 1; i < nums.size(); i += 3) {
/* Checking the elements
in the bucket */
if (nums[i] != nums[i - 1]) {
// Return the single number
return nums[i - 1];
}
}
/* If not found till now, then
the last number will be single */
return nums[n - 1];
}
};
int main() {
vector<int> nums = {2, 2, 2, 3};
/* Creating an instance of
Solution class */
Solution sol;
/* Function call to get the single
number in the given array */
int ans = sol.singleNumber(nums);
cout << "The single number in given array is: " << ans;
return 0;
}
import java.util.Arrays;
class Solution {
/* Function to get the single
number in the given array */
public int singleNumber(int[] nums) {
// Variable to store size of array
int n = nums.length;
// Sorting the array
Arrays.sort(nums);
// Traversing the array
for (int i = 1; i < nums.length; i += 3) {
/* Checking the elements
in the bucket */
if (nums[i] != nums[i - 1]) {
// Return the single number
return nums[i - 1];
}
}
/* If not found till now, then
the last number will be single */
return nums[n - 1];
}
public static void main(String[] args) {
int[] nums = {2, 2, 2, 3};
/* Creating an instance of
Solution class */
Solution sol = new Solution();
/* Function call to get the single
number in the given array */
int ans = sol.singleNumber(nums);
System.out.println("The single number in given array is: " + ans);
}
}
class Solution:
""" Function to get the single
number in the given array """
def singleNumber(self, nums):
# Variable to store size of array
n = len(nums)
# Sorting the array
nums.sort()
# Traversing the array
for i in range(1, len(nums), 3):
""" Checking the elements
in the bucket """
if nums[i] != nums[i - 1]:
# Return the single number
return nums[i - 1]
""" If not found till now, then
the last number will be single """
return nums[n - 1]
# Example usage
nums = [2, 2, 2, 3]
""" Creating an instance of
Solution class """
sol = Solution()
""" Function call to get the single
number in the given array """
ans = sol.singleNumber(nums)
print("The single number in given array is:", ans)
class Solution {
/* Function to get the single
number in the given array */
singleNumber(nums) {
// Variable to store size of array
let n = nums.length;
// Sorting the array
nums.sort((a, b) => a - b);
// Traversing the array
for (let i = 1; i < nums.length; i += 3) {
/* Checking the elements
in the bucket */
if (nums[i] != nums[i - 1]) {
// Return the single number
return nums[i - 1];
}
}
/* If not found till now, then
the last number will be single */
return nums[n - 1];
}
}
// Example usage
let nums = [2, 2, 2, 3];
/* Creating an instance of
Solution class */
let sol = new Solution();
/* Function call to get the single
number in the given array */
let ans = sol.singleNumber(nums);
console.log("The single number in given array is:", ans);
Time Complexity: O(Nlog(N)) –
Space Complexity: O(1) Using a couple of variables i.e., constant space.
The intuition for this approach may not be straightforward and is not typically required in interviews.
The goal is to identify the number that appears only once in an array where all other numbers appear exactly three times. Several observations can help solve this problem.
Imagine using three buckets named Ones, Twos, and Threes to keep track of numbers that appear once, twice, and thrice respectively while iterating through the array. These observations can be made:
&
, |
, ^
), the XOR (^
) operation is particularly useful as it facilitates both addition and removal. Ones = (Ones ^ num) & ~Twos;
Twos = (Twos ^ num) & ~Ones;
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Function to return the number that appears only once
int singleNumber(vector<int>& nums) {
// Two buckets
int ones = 0, twos = 0;
// Traverse the array
for(int i=0; i < nums.size(); i++) {
// Add the number to Ones, it is not in Twos
ones = (ones ^ nums[i]) & ~twos;
// Add the number to Twos, if it is already in Ones
twos = (twos ^ nums[i]) & ~ones;
}
return ones;
}
};
int main() {
vector<int> nums = {1, 0, 3, 0, 1, 1, 3, 3, 10, 0};
// Creating an instance of Solution class
Solution sol;
// Function call to find the number that appears only once
int ans = sol.singleNumber(nums);
cout << "The single number(II) is: " << ans << endl;
return 0;
}
import java.util.*;
class Solution {
public int singleNumber(int[] nums) {
// Two buckets
int ones = 0, twos = 0;
// Traverse the array
for (int i = 0; i < nums.length; i++) {
// Add the number to Ones, if it is not in Twos
ones = (ones ^ nums[i]) & ~twos;
// Add the number to Twos, if it is already in Ones
twos = (twos ^ nums[i]) & ~ones;
}
return ones;
}
}
class Main {
public static void main(String[] args) {
int[] nums = {1, 0, 3, 0, 1, 1, 3, 3, 10, 0};
// Creating an instance of Solution class
Solution sol = new Solution();
// Function call to find the number that appears only once
int ans = sol.singleNumber(nums);
System.out.println("The single number(II) is: " + ans);
}
}
class Solution:
def singleNumber(self, nums):
# Two buckets
ones, twos = 0, 0
# Traverse the array
for num in nums:
# Add the number to Ones, if it is not in Twos
ones = (ones ^ num) & ~twos
# Add the number to Twos, if it is already in Ones
twos = (twos ^ num) & ~ones
return ones
# Main function
if __name__ == "__main__":
nums = [1, 0, 3, 0, 1, 1, 3, 3, 10, 0]
# Creating an instance of Solution class
sol = Solution()
# Function call to find the number that appears only once
ans = sol.singleNumber(nums)
print("The single number(II) is:", ans)
class Solution {
singleNumber(nums) {
// Two buckets
let ones = 0, twos = 0;
// Traverse the array
for (let i = 0; i < nums.length; i++) {
// Add the number to Ones, if it is not in Twos
ones = (ones ^ nums[i]) & ~twos;
// Add the number to Twos, if it is already in Ones
twos = (twos ^ nums[i]) & ~ones;
}
return ones;
}
}
// Main function
const nums = [1, 0, 3, 0, 1, 1, 3, 3, 10, 0];
// Creating an instance of Solution class
const sol = new Solution();
// Function call to find the number that appears only once
const ans = sol.singleNumber(nums);
console.log("The single number(II) is:", ans);
Time Complexity: O(N), where N is the number of elements in the array
Traversing the array once takes linear time.
Space Complexity: O(1), as only a couple of variables are used.
Q: Why can't XOR alone solve this problem?
A: XOR works for cases where every number appears twice except one. However, when numbers appear thrice, XOR fails because it doesn’t account for the triplet elimination logic. Instead, bitwise counting ensures the triplet property is respected.
Q: How does modulo 3 eliminate numbers that appear thrice?
A: For any bit position, the contribution of numbers appearing thrice sums to a multiple of 3. The unique number's contribution remains after applying modulo 3, isolating its bit value.
Q: How would you extend this to handle numbers appearing k-times except one?
A: Modify the approach to count bit frequencies and use modulo k instead of 3 to identify the unique number's bits.
Q: What if multiple numbers appear only once instead of one?
A: The current approach wouldn’t work. For m unique numbers, you’d need to modify the solution to find all such numbers, possibly using a hash set or other data structures.