Hi👋SpeedAlgo • Deliberate Practice & Cognitive Ergonomics for Software Engineers

An interactive algorithm mastery and technical interview preparation platform published by Hi👋WebEnterprise. Built for senior and staff software engineers preparing for rigorous coding screens at top tech companies (FAANG/MAMAA).

13 Core Algorithmic Patterns & 225 Practice Problems

  • 1. Two Pointers (16 Paradigms, 43 Problems): Opposite ends, sorted pair sums, palindrome verification, trapping rain water, 3Sum, container with most water — includes the Sliding Window and Fast & Slow Pointers paradigms (contiguous subarray invariants, longest substrings, Floyd's cycle detection, linked list middle).
  • 2. Binary Search (9 Paradigms, 14 Problems): Monotonic predicate partitioning (feasible(x)), boundary search, rotated sorted arrays, square roots, minimum ship capacity, median of two sorted arrays, matrix median on value range.
  • 3. Bit Manipulation (5 Paradigms, 11 Problems): Counting set bits, XOR cancellation, bit reversal, bitmask pairing, maximum XOR with a bitwise trie.
  • 4. Math & Geometry (8 Paradigms, 14 Problems): Sieve of Eratosthenes, integer/roman conversions, modular arithmetic, geometric simulation.
  • 5. Tree/Graph Depth-First Search (15 Paradigms, 24 Problems): Path sums, lowest common ancestor, tree diameter, validating BSTs, tree DP (House Robber III, Binary Tree Cameras).
  • 6. Tree/Graph Breadth-First Search (5 Paradigms, 12 Problems): Level-order traversals, shortest path in unweighted graphs, zig-zag traversals, rotting oranges, word ladders.
  • 7. Graphs (12 Paradigms, 22 Problems): Topological sort, cycle detection, Dijkstra's algorithm, bipartite graph validation, network delay.
  • 8. Backtracking (6 Paradigms, 14 Problems): Subsets, permutations, combinations, constraint satisfaction, pruning, N-Queens, Sudoku solver.
  • 9. Dynamic Programming (13 Paradigms, 28 Problems): Memoization vs tabulation, 0/1 knapsack, unbounded knapsack, coin change, edit distance, longest common subsequence.
  • 10. Heap / Priority Queue (9 Paradigms, 11 Problems): Running medians, top-k elements, interval scheduling, IPO, k-way merges.
  • 11. Advanced Data Structures (7 Paradigms, 17 Problems): Trie (prefix tree), Union-Find (Disjoint Set Union), LRU Cache, LFU Cache, range-sum queries with updates.
  • 12. Stack (5 Paradigms, 9 Problems): Next greater element, largest rectangle in histogram, remove k digits, decode string, min stack.
  • 13. Intervals & Greedy (2 Paradigms, 6 Problems): Merge intervals, interval scheduling, meeting rooms by sweep line, jump game.

4-Stage Deliberate Practice Framework

  1. Stage 1 (Compare & Learn): Read the pattern's mental model, loop invariant and Big-O proof, compare the pattern's template with the problem's solution side by side, and use the step-by-step debugger. The solution can also be shown in C#, Java, TypeScript, C++, Go or Rust for almost every problem.
  2. Stage 2 (Active Recall): Rebuild the solution from memory in a code editor, with an invariant checklist and optional progressive hints, and check it against a judged test suite.
  3. Stage 3 (AI Interview Coach, coming soon): A mock-interview stage still in development; for now, students go straight from Stage 2 to Stage 4.
  4. Stage 4 (Solve on Your Own): Solve a new problem on your own against a 15-minute timer; your code is graded against a test suite. Python and TypeScript run in your browser and C# runs on our server (design problems grade in Python and TypeScript).

Equipped with a spaced-repetition review hub on a fixed 7-step schedule (1 day up to 90 days), a two-pane Studio workspace, and study notes.

Pricing, Access & Commercial Terms

  • Core Curriculum: 100% Free. No credit card required.
  • Coins: New accounts get 40 free coins once, the daily claim adds +20 coins once a day, and inviting a friend earns you +25 coins when they complete their first practice step. These are the only ways to earn coins.
  • AI Coach: Each AI coach question costs 1-5 coins, priced by the server according to its size.
  • BYOK (Bring Your Own Key): AI coaching is free with your own Google Gemini, OpenAI or OpenRouter API key (BYOK).
  • Extras: Coins also unlock extras for 24 hours: a Recall hint level (1 coin), a Solve solution reveal (2), a LeetCode problem card's solutions (1) and a pattern's extra canonical problems (1).
  • Payments & Refunds: Nothing on the site is sold for money: coins can only be earned, never bought. There are no subscriptions or charges, so there is nothing to refund.
  • Platform Operator: Hi👋WebEnterprise. Support & policies at hispeedalgo.com.
Skip to main content
Hi👋SpeedAlgo

Invariant-First Algorithmic Mastery

Arena
238Items
Theory Context•Bit Manipulation
MediumLC 137

Single Number II (LeetCode 137)

Target Frequency:AmazonMicrosoftGoogle

An integer array nums has every value appearing exactly three times, except for a single value that appears only once. Return that unique value.

Your solution must run in linear time and use only constant extra space.

Worked Examples

Example 1
Input:nums = [2,2,3,2]
Output:3
Explanation: 2 appears three times; 3 appears once.
Example 2
Input:nums = [0,1,0,1,0,1,99]
Output:99
Explanation: 0 and 1 appear three times each; 99 appears once.

⚖️Formal Constraints & Bounds

  • 1 <= nums.length <= 3 * 104

  • -231 <= nums[i] <= 231 - 1

  • Each element in nums appears exactly three times except for one element which appears once.

Deep-Dive & Conceptual Insights

Core Insight

Sum the bits at each of the 32 bit positions modulo 3. Because all other elements appear three times, their bit contributions sum to multiples of 3. The remainder bit at each position forms the binary representation of the unique element.

Real-World Scenario & Production Applications

Fault detection in triple modular redundancy (TMR) systems, sensor majority-voting hardware pipelines, bit-level error isolation.

Step-by-Step Execution Trace Table

Number xBinary Representationtwos FSM Updateones FSM UpdateEffective Modulo-3 Bit State
Init—0000_20000_2All counts 0(mod3)0 \pmod 30(mod3)
20010_20000_20010_2Bit 1 seen once (1(mod3)1 \pmod 31(mod3))
20010_20010_20000_2Bit 1 seen twice (2(mod3)2 \pmod 32(mod3))
30011_20000_20001_2Bit 0: seen once; Bit 1: seen three times (reset to 0(mod3)0 \pmod 30(mod3))
20010_20000_20011_2Bit 0: seen once; Bit 1: seen four times (1(mod3)1 \pmod 31(mod3))
Final—twos = 0ones = 0011_2 (3)Result is ones = 3
Worked on Paper

The Math, Step by Step

1. The count behind each bit

Look at one bit position kkk at a time. Call ckc_kck​ the number of elements of nums that have bit kkk set to 1.

Every value that appears three times adds either 0 or 3 to ckc_kck​. The single value adds 1 if its bit kkk is 1, and 0 if it is 0. So the remainder after dividing ckc_kck​ by 3 is exactly bit kkk of the answer:

ck mod 3=bit k of the single valuec_k \bmod 3 = \text{bit } k \text{ of the single value}ck​mod3=bit k of the single value

Here x mod 3x \bmod 3xmod3 is the remainder after dividing xxx by 3, so it is 0, 1 or 2.

2. Storing the remainder in two bits

The code never computes ckc_kck​. It keeps ck mod 3c_k \bmod 3ck​mod3 while it reads nums, in two integers, ones and twos. Bit kkk of ones and bit kkk of twos together hold the remainder for position kkk:

Remainder ck mod 3c_k \bmod 3ck​mod3Bit kkk of onesBit kkk of twos
000
110
201

When a new element x arrives, its bit kkk is 0 or 1. A 0 leaves the remainder unchanged. A 1 moves the remainder one step: 0 to 1, 1 to 2, and 2 back to 0. The two lines of the loop do exactly this.

Before: ones, twosBit kkk of xAfter ones = (ones ^ x) & ~twosAfter twos = (twos ^ x) & ~onesRemainder
0, 01100 to 1
1, 01011 to 2
0, 11002 to 0
any0unchangedunchangedunchanged

In words: the first line flips the ones bit, unless the twos bit is set. & ~twos keeps a bit only where twos has a 0. The second line flips the twos bit, unless the new ones bit is set.

3. Why one pair of integers counts every bit at once

The operators ^, & and ~ act on each bit position separately. Bit kkk of the result depends only on bit kkk of the inputs. So the two lines run the table of part 2 in every bit position at the same time, with no loop over the bits.

After the last element, every position holds ck mod 3c_k \bmod 3ck​mod3. By part 1, that remainder is 0 or 1 and equals bit kkk of the single value. A remainder of 1 is stored in ones, and twos is 0 everywhere. So ones is the single value, and the code returns it.

4. The order of the two lines

The second line must use the new ones, the value the first line just wrote. With the old ones, the state 0, 0 would become 1, 1 after a bit of 1, which is not a remainder at all. On Example 1, that version returns 0 instead of 3.

Negative values need no special case. Python's bit operators treat a negative number as its two's complement bits, with the sign bit repeated to the left without end. Every one of those positions runs the same table, so ones ends as the negative single value itself. For example, [-2,-2,-2,-5] returns -5.

5. Example 1 by hand

nums = [2,2,3,2]. In binary, 2 is 10 and 3 is 11.

xx in binaryones aftertwos afterRemainder in bit 1Remainder in bit 0
210100010
210001020
311010001
210110011

Bit 1 is set in all four elements, so c1=4c_1 = 4c1​=4 and 4 mod 3=14 \bmod 3 = 14mod3=1. Bit 0 is set only in the 3, so c0=1c_0 = 1c0​=1. Both remainders are 1, so ones ends as 11, which is 3. The code returns 3, the expected output.

6. Example 2 by hand

nums = [0,1,0,1,0,1,99]. The 0s change nothing. The three 1s move the remainder of bit 0 from 0 to 1, to 2, and back to 0. So after the first six elements, ones and twos are both 0.

xones aftertwos after
000
110
010
101
001
100
99990

The last element, 99, is 1100011 in binary. Each of its set bits moves a remainder from 0 to 1, so ones becomes 99. The code returns 99, the expected output.

7. From the counts to the code
MathIn singleNumber
every remainder starts at 0ones = 0 and twos = 0
remainder 1 in bit kkkbit kkk of ones is 1
remainder 2 in bit kkkbit kkk of twos is 1
a bit of 1 moves the remainder one stepones = (ones ^ x) & ~twos then twos = (twos ^ x) & ~ones
ck mod 3c_k \bmod 3ck​mod3 is the answer's bit kkkreturn ones

The loop does a fixed number of bit operations per element, so it takes O(n)O(n)O(n) time. It keeps two integers, so it uses O(1)O(1)O(1) extra space.

Code Shape
Archetype Code Shape
Python
1ones = 0
2twos = 0
3for x in nums:
4 ones = (ones ^ x) & ~twos
5 twos = (twos ^ x) & ~ones
6return ones

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

Given an integer array where every element appears three times except for one element which appears exactly once, simple XOR fails because x⊕x⊕x=xx \oplus x \oplus x = xx⊕x⊕x=x (an odd number of occurrences does not cancel). To isolate the unique element without extra space (O(1)O(1)O(1) space), we must simulate a 3-state counter for each of the 32 bit positions simultaneously: 0→1→2→00 \to 1 \to 2 \to 00→1→2→0.

🏟️ The Analogy: The 3-Position Revolving Turnstile

Imagine 32 miniature revolving turnstiles side by side, each with 3 prongs marked 0, 1, and 2. Whenever an incoming number has a set bit at position iii, turnstile iii pushes forward by one notch. If a number appears 3 times, its set bits turn their corresponding turnstiles by 3 clicks, returning them exactly to 0. The solitary number clicks its turnstiles once, leaving them resting at position 1.

🔑 Why It Works

The state machine truth table per bit:

  • State (0, 0) + bit 1 →\to→ (1, 0) (appeared once)
  • State (1, 0) + bit 1 →\to→ (0, 1) (appeared twice)
  • State (0, 1) + bit 1 →\to→ (0, 0) (appeared three times, reset!) After iterating through all elements, all triplets reset to 0, leaving the unique single element in ones.
  • Python arbitrary precision negative two's complement: Python integers do not overflow at 32 bits; negative numbers have infinite sign bits. To correctly reconstruct signed 32-bit integers from bit counts, mask with 0xFFFFFFFF and convert if bit 31 is set: res if res < (1 << 31) else ~(res ^ 0xFFFFFFFF).

  • Modulo-3 state machine transition confusion: The two variables ones and twos track bits appearing 1(mod3)1 \pmod 31(mod3) and 2(mod3)2 \pmod 32(mod3). Updating ones = (ones ^ n) & ~twos and twos = (twos ^ n) & ~ones must preserve state ordering.

  • Shifting more than 31 bits in 32-bit types: In C++/Java, 1 << 32 is undefined behavior. Only shift up to 31 bits.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Array where every element appears 3 times except one unique element, O(N) time and O(1) space constraint.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: ones tracks bits seen 1 mod 3 times; twos tracks bits seen 2 mod 3 times. Bits seen 3 times reset to 0 in both registers.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Using standard XOR cancellation: XOR only cancels pairs (x ^ x = 0); with triples, x ^ x ^ x = x, creating false positives.

  • if res >= 231: res -= 232 in the per-bit version: res is built as an unsigned 32-bit value, so without it [-2, -2, -2, -4] returns 4294967292 instead of -4.

  • State transition order: twos must be computed from the new ones; swapping the two update lines makes [2, 2, 3, 2] return 0 instead of 3.

The 60-Second Interview Pitch

Say this out loud before you type a single line

This is Per-Bit Counting. Every number except one appears three times, so at each bit position those copies add a multiple of three, and the count modulo three is exactly the single number's bit. I keep that count for all 32 positions at once in two registers: a bit is set in ones when its count so far is one mod three, and in twos when it is two. Each number moves its bits one step through zero, one, two and back to zero. I update ones first and then twos from the new ones; swapping those two lines breaks the count. At the end ones holds the answer. That is one pass, so O(N) time, and two integers, so O(1) space.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at the execution steps: Tracks bit states appearing 1, 2, or 3 times using two bitmask accumulators (ones, twos). When bit appears 3 times, cleared from both. Single pass through N elements.

SPACE COMPLEXITY

O(1) Auxiliary

Look at memory allocations: Call stack uses O(1) Iterative. Two scalar integer bitmask variables (ones, twos).

Formal Recurrence Relation

T(N) = N · O(1) = O(N)

Derivation Progression

Loop Count

for x in nums → N iterations

One pass over the N numbers.

Work per Iteration

2 register updates → O(1)

Two updates on two integers, whatever the value of x.

Final Answer Extraction

return ones

ones holds unique element appearing exactly once in O(1) space.

Variable Definitions

NNN

Total number of elements in the array

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(1) Two 32-bit registers

🟢 Output Space

O(1) Single number integer

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N)

Average Case

O(N)O(N)O(N)

Worst Case

O(N)O(N)O(N)

Recurrence Tree Topology

Recurrence Tree Topology
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

The problem states: each value shows up three times, apart from one value that shows up only once. Plain XOR fails here because x⊕x⊕x=xx \oplus x \oplus x = xx⊕x⊕x=x, meaning duplicates do not cancel to 0! To make elements appearing 3 times cancel out, each bit position must be counted modulo 3. This triggers a Bit-Level Mod-3 Finite State Machine (FSM).

CONSTRAINTS & BOUNDS

N≤3×104N \le 3 \times 10^4N≤3×104, elements fit in 32-bit signed integers. Space must strictly be O(1)O(1)O(1). Counting bits with an array of size 32 takes O(32N)O(32N)O(32N) time, but synthesizing a 2-bit counter using two 32-bit integer registers (ones and twos) processes all 32 bit-positions in parallel in a single O(N)O(N)O(N) pass.

FAANG PRODUCTION TRAPS & EDGE CASES

The trap is failing to clear bits when the count transitions from 2 to 3 (which must wrap to 0). The mask ~twos ensures that if a bit was already in twos, it doesn't stay in ones. Negative numbers in Python must be handled if 32-bit two's complement sign extension occurs, though in LC 137 standard signed operations produce the correct signed integer.

Theory Context•Bit Manipulation
MediumLC 137

Single Number II (LeetCode 137)

Target Frequency:AmazonMicrosoftGoogle

An integer array nums has every value appearing exactly three times, except for a single value that appears only once. Return that unique value.

Your solution must run in linear time and use only constant extra space.

Worked Examples

Example 1
Input:nums = [2,2,3,2]
Output:3
Explanation: 2 appears three times; 3 appears once.
Example 2
Input:nums = [0,1,0,1,0,1,99]
Output:99
Explanation: 0 and 1 appear three times each; 99 appears once.

⚖️Formal Constraints & Bounds

  • 1 <= nums.length <= 3 * 104

  • -231 <= nums[i] <= 231 - 1

  • Each element in nums appears exactly three times except for one element which appears once.

Deep-Dive & Conceptual Insights

Core Insight

Sum the bits at each of the 32 bit positions modulo 3. Because all other elements appear three times, their bit contributions sum to multiples of 3. The remainder bit at each position forms the binary representation of the unique element.

Real-World Scenario & Production Applications

Fault detection in triple modular redundancy (TMR) systems, sensor majority-voting hardware pipelines, bit-level error isolation.

Step-by-Step Execution Trace Table

Number xBinary Representationtwos FSM Updateones FSM UpdateEffective Modulo-3 Bit State
Init—0000_20000_2All counts 0(mod3)0 \pmod 30(mod3)
20010_20000_20010_2Bit 1 seen once (1(mod3)1 \pmod 31(mod3))
20010_20010_20000_2Bit 1 seen twice (2(mod3)2 \pmod 32(mod3))
30011_20000_20001_2Bit 0: seen once; Bit 1: seen three times (reset to 0(mod3)0 \pmod 30(mod3))
20010_20000_20011_2Bit 0: seen once; Bit 1: seen four times (1(mod3)1 \pmod 31(mod3))
Final—twos = 0ones = 0011_2 (3)Result is ones = 3
Worked on Paper

The Math, Step by Step

1. The count behind each bit

Look at one bit position kkk at a time. Call ckc_kck​ the number of elements of nums that have bit kkk set to 1.

Every value that appears three times adds either 0 or 3 to ckc_kck​. The single value adds 1 if its bit kkk is 1, and 0 if it is 0. So the remainder after dividing ckc_kck​ by 3 is exactly bit kkk of the answer:

ck mod 3=bit k of the single valuec_k \bmod 3 = \text{bit } k \text{ of the single value}ck​mod3=bit k of the single value

Here x mod 3x \bmod 3xmod3 is the remainder after dividing xxx by 3, so it is 0, 1 or 2.

2. Storing the remainder in two bits

The code never computes ckc_kck​. It keeps ck mod 3c_k \bmod 3ck​mod3 while it reads nums, in two integers, ones and twos. Bit kkk of ones and bit kkk of twos together hold the remainder for position kkk:

Remainder ck mod 3c_k \bmod 3ck​mod3Bit kkk of onesBit kkk of twos
000
110
201

When a new element x arrives, its bit kkk is 0 or 1. A 0 leaves the remainder unchanged. A 1 moves the remainder one step: 0 to 1, 1 to 2, and 2 back to 0. The two lines of the loop do exactly this.

Before: ones, twosBit kkk of xAfter ones = (ones ^ x) & ~twosAfter twos = (twos ^ x) & ~onesRemainder
0, 01100 to 1
1, 01011 to 2
0, 11002 to 0
any0unchangedunchangedunchanged

In words: the first line flips the ones bit, unless the twos bit is set. & ~twos keeps a bit only where twos has a 0. The second line flips the twos bit, unless the new ones bit is set.

3. Why one pair of integers counts every bit at once

The operators ^, & and ~ act on each bit position separately. Bit kkk of the result depends only on bit kkk of the inputs. So the two lines run the table of part 2 in every bit position at the same time, with no loop over the bits.

After the last element, every position holds ck mod 3c_k \bmod 3ck​mod3. By part 1, that remainder is 0 or 1 and equals bit kkk of the single value. A remainder of 1 is stored in ones, and twos is 0 everywhere. So ones is the single value, and the code returns it.

4. The order of the two lines

The second line must use the new ones, the value the first line just wrote. With the old ones, the state 0, 0 would become 1, 1 after a bit of 1, which is not a remainder at all. On Example 1, that version returns 0 instead of 3.

Negative values need no special case. Python's bit operators treat a negative number as its two's complement bits, with the sign bit repeated to the left without end. Every one of those positions runs the same table, so ones ends as the negative single value itself. For example, [-2,-2,-2,-5] returns -5.

5. Example 1 by hand

nums = [2,2,3,2]. In binary, 2 is 10 and 3 is 11.

xx in binaryones aftertwos afterRemainder in bit 1Remainder in bit 0
210100010
210001020
311010001
210110011

Bit 1 is set in all four elements, so c1=4c_1 = 4c1​=4 and 4 mod 3=14 \bmod 3 = 14mod3=1. Bit 0 is set only in the 3, so c0=1c_0 = 1c0​=1. Both remainders are 1, so ones ends as 11, which is 3. The code returns 3, the expected output.

6. Example 2 by hand

nums = [0,1,0,1,0,1,99]. The 0s change nothing. The three 1s move the remainder of bit 0 from 0 to 1, to 2, and back to 0. So after the first six elements, ones and twos are both 0.

xones aftertwos after
000
110
010
101
001
100
99990

The last element, 99, is 1100011 in binary. Each of its set bits moves a remainder from 0 to 1, so ones becomes 99. The code returns 99, the expected output.

7. From the counts to the code
MathIn singleNumber
every remainder starts at 0ones = 0 and twos = 0
remainder 1 in bit kkkbit kkk of ones is 1
remainder 2 in bit kkkbit kkk of twos is 1
a bit of 1 moves the remainder one stepones = (ones ^ x) & ~twos then twos = (twos ^ x) & ~ones
ck mod 3c_k \bmod 3ck​mod3 is the answer's bit kkkreturn ones

The loop does a fixed number of bit operations per element, so it takes O(n)O(n)O(n) time. It keeps two integers, so it uses O(1)O(1)O(1) extra space.

Code Shape
Archetype Code Shape
Python
1ones = 0
2twos = 0
3for x in nums:
4 ones = (ones ^ x) & ~twos
5 twos = (twos ^ x) & ~ones
6return ones

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

Given an integer array where every element appears three times except for one element which appears exactly once, simple XOR fails because x⊕x⊕x=xx \oplus x \oplus x = xx⊕x⊕x=x (an odd number of occurrences does not cancel). To isolate the unique element without extra space (O(1)O(1)O(1) space), we must simulate a 3-state counter for each of the 32 bit positions simultaneously: 0→1→2→00 \to 1 \to 2 \to 00→1→2→0.

🏟️ The Analogy: The 3-Position Revolving Turnstile

Imagine 32 miniature revolving turnstiles side by side, each with 3 prongs marked 0, 1, and 2. Whenever an incoming number has a set bit at position iii, turnstile iii pushes forward by one notch. If a number appears 3 times, its set bits turn their corresponding turnstiles by 3 clicks, returning them exactly to 0. The solitary number clicks its turnstiles once, leaving them resting at position 1.

🔑 Why It Works

The state machine truth table per bit:

  • State (0, 0) + bit 1 →\to→ (1, 0) (appeared once)
  • State (1, 0) + bit 1 →\to→ (0, 1) (appeared twice)
  • State (0, 1) + bit 1 →\to→ (0, 0) (appeared three times, reset!) After iterating through all elements, all triplets reset to 0, leaving the unique single element in ones.
  • Python arbitrary precision negative two's complement: Python integers do not overflow at 32 bits; negative numbers have infinite sign bits. To correctly reconstruct signed 32-bit integers from bit counts, mask with 0xFFFFFFFF and convert if bit 31 is set: res if res < (1 << 31) else ~(res ^ 0xFFFFFFFF).

  • Modulo-3 state machine transition confusion: The two variables ones and twos track bits appearing 1(mod3)1 \pmod 31(mod3) and 2(mod3)2 \pmod 32(mod3). Updating ones = (ones ^ n) & ~twos and twos = (twos ^ n) & ~ones must preserve state ordering.

  • Shifting more than 31 bits in 32-bit types: In C++/Java, 1 << 32 is undefined behavior. Only shift up to 31 bits.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Array where every element appears 3 times except one unique element, O(N) time and O(1) space constraint.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: ones tracks bits seen 1 mod 3 times; twos tracks bits seen 2 mod 3 times. Bits seen 3 times reset to 0 in both registers.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Using standard XOR cancellation: XOR only cancels pairs (x ^ x = 0); with triples, x ^ x ^ x = x, creating false positives.

  • if res >= 231: res -= 232 in the per-bit version: res is built as an unsigned 32-bit value, so without it [-2, -2, -2, -4] returns 4294967292 instead of -4.

  • State transition order: twos must be computed from the new ones; swapping the two update lines makes [2, 2, 3, 2] return 0 instead of 3.

The 60-Second Interview Pitch

Say this out loud before you type a single line

This is Per-Bit Counting. Every number except one appears three times, so at each bit position those copies add a multiple of three, and the count modulo three is exactly the single number's bit. I keep that count for all 32 positions at once in two registers: a bit is set in ones when its count so far is one mod three, and in twos when it is two. Each number moves its bits one step through zero, one, two and back to zero. I update ones first and then twos from the new ones; swapping those two lines breaks the count. At the end ones holds the answer. That is one pass, so O(N) time, and two integers, so O(1) space.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at the execution steps: Tracks bit states appearing 1, 2, or 3 times using two bitmask accumulators (ones, twos). When bit appears 3 times, cleared from both. Single pass through N elements.

SPACE COMPLEXITY

O(1) Auxiliary

Look at memory allocations: Call stack uses O(1) Iterative. Two scalar integer bitmask variables (ones, twos).

Formal Recurrence Relation

T(N) = N · O(1) = O(N)

Derivation Progression

Loop Count

for x in nums → N iterations

One pass over the N numbers.

Work per Iteration

2 register updates → O(1)

Two updates on two integers, whatever the value of x.

Final Answer Extraction

return ones

ones holds unique element appearing exactly once in O(1) space.

Variable Definitions

NNN

Total number of elements in the array

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(1) Two 32-bit registers

🟢 Output Space

O(1) Single number integer

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N)

Average Case

O(N)O(N)O(N)

Worst Case

O(N)O(N)O(N)

Recurrence Tree Topology

Recurrence Tree Topology
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

The problem states: each value shows up three times, apart from one value that shows up only once. Plain XOR fails here because x⊕x⊕x=xx \oplus x \oplus x = xx⊕x⊕x=x, meaning duplicates do not cancel to 0! To make elements appearing 3 times cancel out, each bit position must be counted modulo 3. This triggers a Bit-Level Mod-3 Finite State Machine (FSM).

CONSTRAINTS & BOUNDS

N≤3×104N \le 3 \times 10^4N≤3×104, elements fit in 32-bit signed integers. Space must strictly be O(1)O(1)O(1). Counting bits with an array of size 32 takes O(32N)O(32N)O(32N) time, but synthesizing a 2-bit counter using two 32-bit integer registers (ones and twos) processes all 32 bit-positions in parallel in a single O(N)O(N)O(N) pass.

FAANG PRODUCTION TRAPS & EDGE CASES

The trap is failing to clear bits when the count transitions from 2 to 3 (which must wrap to 0). The mask ~twos ensures that if a bit was already in twos, it doesn't stay in ones. Negative numbers in Python must be handled if 32-bit two's complement sign extension occurs, though in LC 137 standard signed operations produce the correct signed integer.

© 2026 Hi👋WebEnterprise. All rights reserved.
Sitemap•llms.txt•