Skip to content
Programmingoneonone
Programmingoneonone
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
    • Cybersecurity
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programmingoneonone
Programmingoneonone

Leetcode Single Number II problem solution

YASH PAL, 31 July 202419 January 2026

In this Leetcode Single Number II problem solution, we have 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.

Leetcode Single Number II problem solution

Leetcode Single Number II problem solution in Python.

def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return int((3*sum(set(nums))-sum(nums))/2)

Single Number II problem solution in Java.

class Solution {
    public int singleNumber(int[] nums) {
        Map<Integer,Integer> map = new HashMap();
        for(int i=0;i<nums.length;i++){
            if(map.containsKey(nums[i])){
                map.put(nums[i],map.get(nums[i])+1);
            }
            else{
                map.put(nums[i],1);
            }
        }
        for(Integer values: map.keySet()){
            if(map.get(values)==1){
                return values;
            }
        }
        return -1;
    }
}

Problem solution in C++.

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int i=0;
        int j=0;
        for(int k:nums){
            i=~j&(i^k);
            j=~i&(j^k);
        }
      return i ;  
    }
};

Problem solution in C.

int partition(int *nums, int l, int r){
    int i = l,j = l;
    int t = l + rand()%(r-l+1);
    int tmp,p;
    p = nums[t];
    nums[t] = nums[r];
    nums[r] = p;
    
    for ( ; i <= r; i++){
        if (nums[i] <= p ){
            tmp = nums[i];
            nums[i] = nums[j];
            nums[j++] = tmp;
        }
    }return j;
}

int singleNumber(int* nums, int numsSize) {
    int i = 0, j = numsSize-1;
    int par;
    while(i<j){
        par = partition(nums,i,j);
        if (par%3 == 0){
            i = par;
        } else j = par-1;
    }
    return nums[i];
}

coding problems solutions Leetcode Problems Solutions Leetcode

Post navigation

Previous post
Next post

Leave a Reply

Your email address will not be published. Required fields are marked *

Pages

  • About US
  • Contact US
  • Privacy Policy

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes