← Home

136. Single Number

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
bit manipulationC++Markdown
136

Let's make this one less mysterious. For 136. Single Number, the solution in this repository is mainly a bit manipulation solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: bit manipulation.

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are singleNumber.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • A set is doing the membership or uniqueness work, which keeps the main loop readable.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02Given a non-empty array of integers, every element appears twice except for one. Find that single one.
03
04Note:
05
06Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
07
08Example 1:
09
10Input: [2,2,1]
11Output: 1
12Example 2:
13
14Input: [4,1,2,1,2]
15Output: 4
16**/
17
18//Runtime: 36 ms, faster than 7.03% of C++ online submissions for Single Number.
19//Memory Usage: 11.9 MB, less than 5.09% of C++ online submissions for Single Number.
20class Solution {
21public:
22    int singleNumber(vector<int>& nums) {
23        map<int, int> mymap;
24        
25        for(int num : nums){
26            if(mymap.find(num)==mymap.end()){
27                mymap[num] = 1;
28            }else{
29                mymap[num] += 1;
30            }
31        }
32        
33        for(map<int, int>::iterator it=mymap.begin(); it!=mymap.end(); it++){
34            if(it->second==1) return it->first;
35        }
36        
37        return -1;
38    }
39};
40
41//using set
42//Runtime: 32 ms, faster than 10.91% of C++ online submissions for Single Number.
43//Memory Usage: 11.8 MB, less than 5.09% of C++ online submissions for Single Number.
44/**
45class Solution {
46public:
47    int singleNumber(vector<int>& nums) {
48        set<int> myset;
49        
50        for(int num : nums){
51            if(myset.find(num)==myset.end()){
52                myset.insert(num);
53            }else{
54                myset.erase(num);
55            }
56        }
57        
58        if(!myset.empty()){
59            return *myset.begin();
60        }
61        
62        return -1;
63    }
64};
65**/
66
67
68//math
69//2∗(a+b+c)−(a+a+b+b+c)=c
70/**
71Complexity Analysis
72
73Time complexity : O(n + n) = O(n). sum will call next to iterate through nums. 
74We can see it as sum(list(i, for i in nums)) which means the time complexity is O(n) 
75because of the number of elements(n) in nums.
76
77Space complexity : O(n + n) = O(n). set needs space for the elements in nums **/
78
79//Runtime: 36 ms, faster than 7.05% of C++ online submissions for Single Number.
80//Memory Usage: 11.8 MB, less than 5.09% of C++ online submissions for Single Number.
81
82/**
83class Solution {
84public:
85    int singleNumber(vector<int>& nums) {
86        set<int> myset (nums.begin(), nums.end());
87        int ans = 0;
88        
89        for(int e : myset){
90            ans += e*2;
91        }
92        
93        for(int e : nums){
94            ans -= e;
95        }
96        
97        return ans;
98    }
99};
100**/
101
102/**
103Approach 4: Bit Manipulation
104Concept
105
106If we take XOR of zero and some bit, it will return that bit
107a⊕0=a
108If we take XOR of two same bits, it will return 0
109a⊕a=0
110a⊕b⊕a=(a⊕a)⊕b=0⊕b=b
111So we can XOR all bits together to find the unique number.
112**/
113
114/**
115Complexity Analysis
116
117Time complexity : O(n). 
118We only iterate through nums, 
119so the time complexity is the number of elements in nums.
120
121Space complexity : O(1).
122**/
123
124//Runtime: 16 ms, faster than 96.66% of C++ online submissions for Single Number.
125//Memory Usage: 9.6 MB, less than 92.26% of C++ online submissions for Single Number.
126
127/**
128class Solution {
129public:
130    int singleNumber(vector<int>& nums) {
131        int ans=0;
132        
133        for(int num : nums){
134            ans^=num;
135        }
136        
137        return ans;
138    }
139};
140**/

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.