137. Single Number II LeetCode

 Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it.


You must implement a solution with a linear runtime complexity and use only constant extra space.


 


Example 1:


Input: nums = [2,2,3,2]

Output: 3

Example 2:


Input: nums = [0,1,0,1,0,1,99]

Output: 99

 


Approach 1 : Use Extra Space

class Solution {
    public int singleNumber(int[] nums) {
       
        HashMap<Integer,Integer> map= new HashMap<>();

        for(int num :nums)
        {
             map.put(num, map.getOrDefault(num, 0) + 1);
        }

        int count=0;

        for(Map.Entry<Integer,Integer> entry:map.entrySet())
        {
            if(entry.getValue()==1)
            {
                return entry.getKey();
            }
        }
        return -1;
    }
}


Approach 2 :Use only constant extra space 

Bitwise approach:-

keyConcept -use left shift and use check at kth position bit is 0 or 1


🧠 Key Insight:

Use bit manipulation:

  • Count how many times each bit (0–31) is set in all numbers.

  • If a bit is set in the unique number, it will not be a multiple of 3.

  • Use left shift to create masks and count set bits.

class Solution {
    public int singleNumber(int[] nums) {
        int result = 0;

        for (int i = 0; i < 32; i++) {
            int mask = 1 << i;
            int countZero = 0;
            int countOne = 0;

            for (int num : nums) {
                if ((num & mask) == 0) {
                    countZero++;
                } else {
                    countOne++;
                }
            }

            if (countOne % 3 != 0) {
                result |= mask;
            }
        }

        return result;
    }
}



Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence