Skip to content
Programming101
Programming101

Learn everything about programming

  • Home
  • CS Subjects
    • IoT – Internet of Things
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programming101

Learn everything about programming

Leetcode Single Number II problem solution

YASH PAL, 31 July 2024

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

Problem solution in Python.

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

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

Post navigation

Previous post
Next post
  • How AI Is Revolutionizing Personalized Learning in Schools
  • GTA 5 is the Game of the Year for 2024 and 2025
  • Hackerrank Day 5 loops 30 days of code solution
  • Hackerrank Day 6 Lets Review 30 days of code solution
  • Hackerrank Day 14 scope 30 days of code solution
©2025 Programming101 | WordPress Theme by SuperbThemes