Single Number II - Problem

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 linear runtime complexity and use only constant extra space.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,2,3,2]
Output: 3
💡 Note: Element 2 appears 3 times, element 3 appears 1 time. Return 3.
Example 2 — Larger Array
$ Input: nums = [0,1,0,1,0,1,99]
Output: 99
💡 Note: Elements 0 and 1 each appear 3 times, element 99 appears 1 time. Return 99.
Example 3 — Single Element
$ Input: nums = [5]
Output: 5
💡 Note: Only one element in array, it appears once. Return 5.

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.

Visualization

Tap to expand
Single Number II - Bit Manipulation INPUT nums = [2, 2, 3, 2] 2 2 3 2 [0] [1] [2] [3] Element Frequency: 2 appears 3 times 3 appears 1 time Binary Form: 2 = 10 (binary) 3 = 11 (binary) O(n) time, O(1) space required ALGORITHM STEPS 1 Use Two Variables ones, twos track bits 2 For Each Number Update ones and twos 3 Bit Logic ones = (ones^n) & ~twos 4 Return ones Contains single number Trace Execution: num ones twos init 0 0 2 2 0 2 0 2 3 3 2 FINAL RESULT Single Element Found! 3 Output Verification: 2 appears 3 times - OK 3 appears 1 time - FOUND Complexity Analysis Time: O(n) - single pass Space: O(1) - two vars Key Insight: Use two variables (ones, twos) to count bits modulo 3. For bits appearing 3 times, they cycle through: ones only --> twos only --> neither. The single number's bits appear only once, so they remain in 'ones'. Formula: ones = (ones XOR n) AND (NOT twos) TutorialsPoint - Single Number II | Optimal Bit Manipulation Solution
Asked in
Google 25 Microsoft 20 Amazon 18 Apple 15
89.0K Views
Medium Frequency
~25 min Avg. Time
2.9K 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