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
๐Ÿ•ต๏ธ The Frequency DetectiveCrime Scene: [3, 3, 2, 3, 1, 1]3Normal32Suspect A31Suspect B1๐Ÿ” Detective's Evidence BoardElement 3Seen 3 timesElement 2Seen 1 time โš ๏ธElement 1Seen 2 times โš ๏ธCASE SOLVED![2, 1]๐Ÿ’ก Detective Tools:โ€ข Hash Map: O(n) time, O(n) space - Good but uses extra evidence storageโ€ข Bit Manipulation: O(n) time, O(1) space - Expert detective work!
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.
Asked in
Google 42 Amazon 38 Meta 25 Microsoft 18
52.3K Views
Medium Frequency
~18 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