Once Twice - Problem
You're given an integer array with a unique frequency pattern: exactly one element appears once, exactly one element appears twice, and all other elements appear exactly three times.
Your mission is to identify the two special elements and return them as an array: [once_element, twice_element].
Challenge: Solve this in O(n) time and O(1) space!
Example: In array [3, 3, 2, 3, 1, 1], element 2 appears once and element 1 appears twice, so return [2, 1].
Input & Output
example_1.py โ Basic Case
$
Input:
[3, 3, 2, 3, 1, 1]
โบ
Output:
[2, 1]
๐ก Note:
Element 2 appears once, element 1 appears twice, and element 3 appears three times. Return [2, 1].
example_2.py โ Different Order
$
Input:
[1, 1, 2, 3, 3, 3]
โบ
Output:
[2, 1]
๐ก Note:
Element 2 appears once, element 1 appears twice, element 3 appears three times. Order in array doesn't matter.
example_3.py โ Negative Numbers
$
Input:
[-1, -1, 0, 2, 2, 2]
โบ
Output:
[0, -1]
๐ก Note:
Element 0 appears once, element -1 appears twice, element 2 appears three times. Works with negative numbers too.
Constraints
- 3 โค nums.length โค 3 ร 104
- -3 ร 104 โค nums[i] โค 3 ร 104
- Exactly one element appears once
- Exactly one element appears twice
- All other elements appear exactly three times
- Solution must run in O(n) time and O(1) space
Visualization
Tap to expand
Understanding the Visualization
1
Crime Scene Analysis
You have an array where most elements appear 3 times (normal citizens), but two are special
2
Frequency Investigation
Count how many times each number appears using your detective tools (hash map or bit manipulation)
3
Identify Suspects
The element appearing once is suspect A, the element appearing twice is suspect B
4
Case Closed
Return both suspects as [suspect_A, suspect_B]
Key Takeaway
๐ฏ Key Insight: Like a skilled detective, you can identify the special elements by their unique frequency signatures - one appears once, one appears twice, while all others appear three times.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code