Once Twice - Problem

You are given an integer array nums with the following properties:

  • Exactly one element appears once
  • Exactly one element appears twice
  • All other elements appear exactly three times

Return an integer array of length 2, where:

  • The first element is the one that appears once
  • The second element is the one that appears twice

Your solution must run in O(n) time and O(1) space.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,1,3,1,3,3,2]
Output: [1,2]
💡 Note: Element 1 appears once, element 2 appears twice, element 3 appears three times. Return [1,2].
Example 2 — Different Numbers
$ Input: nums = [4,4,4,5,6,5]
Output: [6,5]
💡 Note: Element 6 appears once, element 5 appears twice, element 4 appears three times. Return [6,5].
Example 3 — Minimum Length
$ Input: nums = [0,1,0,0,2,2]
Output: [1,2]
💡 Note: Element 0 appears three times, element 1 appears once, element 2 appears twice. Return [1,2].

Constraints

  • 3 ≤ nums.length ≤ 3 × 104
  • -231 ≤ nums[i] ≤ 231 - 1
  • Each integer appears either 1, 2, or 3 times
  • Exactly one integer appears once
  • Exactly one integer appears twice

Visualization

Tap to expand
Once Twice - Finding Unique Elements INPUT nums = [2,1,3,2,3,2,3] 2 1 3 2 3 2 3 Element Counts: Value Count 1 1 (once) 2 2 (twice) 3 3 (thrice) ALGORITHM STEPS 1 Bit Manipulation Track bits appearing 1x, 2x, 3x times 2 Use Three Variables ones: bits seen 1x twos: bits seen 2x 3 XOR Operations ones ^= num twos ^= num 4 Filter Threes Remove bits that appear 3 times Core Logic: threes = ones & twos ones &= ~threes twos &= ~threes FINAL RESULT After processing all elements: ones = 1 (appears exactly once) twos = 2 (appears exactly twice) OUTPUT [1, 2] OK - Verified! 1 appears 1 time 2 appears 2 times 3 appears 3 times Key Insight: Using bit manipulation with XOR, we can track which bits appear 1x, 2x, or 3x times. After processing, 'ones' holds the element appearing once, 'twos' holds the element appearing twice. Time: O(n) single pass | Space: O(1) using only three integer variables. TutorialsPoint - Once Twice | Optimal Solution (Bit Manipulation)
Asked in
Facebook 25 Google 20 Amazon 15 Microsoft 12
23.4K Views
Medium Frequency
~25 min Avg. Time
890 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