Single Number II
Master this topic with zero to advance depth.
Single Number II
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.
Examples
Level I: Brute Force (Frequency Map)
Intuition
The simplest way to track occurrences is using a hash map or frequency array. We count how many times each number appears and return the one with a count of 1.
Level II: Sorting
Intuition
If we sort the numbers, identical numbers will be adjacent. We can jump in steps of 3 and check if nums[i] is different from nums[i+1].
Level III: Optimal (Bit Manipulation)
Intuition
Every number that appears three times will contribute exactly 3 (or 0) to the sum of bits at any given position. If we sum the bits at each position and take modulo 3, the remaining bit belongs to the single number.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.