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: Find the Unique ElementInput: [2,2,3,2] → All appear 3 times except one2232appearsappearsappearsappears3 times3 times1 time3 timesBit manipulation tracks count modulo 3Elements appearing 3 times cancel outOutput: 3Time: O(n), Space: O(1)
Understanding the Visualization
1
Input
Array where all elements appear 3 times except one
2
Process
Use bit manipulation to track occurrences
3
Output
Return the single unique element
Key Takeaway
🎯 Key Insight: Use bit manipulation to count occurrences modulo 3, allowing constant space 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