Single Number II - Problem

Imagine you're analyzing data from a survey where almost every response appears exactly three times in your dataset, but there's one special response that appears only once. Your task is to efficiently identify this unique response.

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

Challenge: Your solution must run in O(n) time and use only O(1) extra space - no sorting allowed!

Example: In array [2,2,3,2], the number 3 appears once while 2 appears three times, so return 3.

Input & Output

example_1.py โ€” Basic Case
$ Input: [2,2,3,2]
โ€บ Output: 3
๐Ÿ’ก Note: Element 2 appears 3 times, element 3 appears 1 time. The single number is 3.
example_2.py โ€” Negative Numbers
$ Input: [0,1,0,1,0,1,99]
โ€บ Output: 99
๐Ÿ’ก Note: Elements 0 and 1 each appear 3 times, element 99 appears 1 time. The single number is 99.
example_3.py โ€” Single Element Array
$ Input: [1]
โ€บ Output: 1
๐Ÿ’ก Note: Only one element in the array, so it's the single number by definition.

Visualization

Tap to expand
Bit Manipulation MagicState Machine Logic:โ€ข ones ^= num (XOR toggles first occurrence)โ€ข twos |= ones & num (OR records second occurrence)โ€ข When 3rd occurrence detected:โ€ข Both ones and twos reset that bit to 00Start1First2Secondsee bitsee bitsee bit (3rd time)Result: Only the single number survives!All bits appearing 3 times get eliminated, leaving only bits from the single number
Understanding the Visualization
1
Initialize Counters
Set up two binary counters: 'ones' for first occurrence, 'twos' for second occurrence
2
Process Each Number
For each number, update both counters using bit manipulation rules
3
Auto-Reset on Triplets
When a bit appears 3 times, both counters automatically reset that bit to 0
4
Extract Result
The 'ones' counter contains only bits from the single number
Key Takeaway
๐ŸŽฏ Key Insight: Use mathematical properties of XOR and bit tracking to eliminate elements that appear in multiples of 3, leaving only the single element

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass to build hash map + single pass to find answer

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Hash map stores at most n/3 unique elements in worst case

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 3 ร— 104
  • -231 โ‰ค nums[i] โ‰ค 231 - 1
  • Each element in the array appears exactly three times except for one element which appears exactly once
Asked in
Google 45 Microsoft 38 Amazon 32 Apple 28
42.0K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen