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
EasyLC 136

Single Number (LeetCode 136)

Target Frequency:GoogleMetaAmazon

You're given a non-empty array of integers nums where every value shows up twice except for exactly one value that shows up only once. Return that lone value.

Your solution must run in linear time and use only constant extra space — no sorting, no hash map.

Worked Examples

Example 1
Input:nums = [2,2,1]
Output:1
Explanation: 2 appears twice; 1 appears once.
Example 2
Input:nums = [4,1,2,1,2]
Output:4
Explanation: 1 and 2 each appear twice; 4 appears once.
Example 3
Input:nums = [1]
Output:1
Explanation: The only element is the answer.

⚖️Formal Constraints & Bounds

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

  • -3 * 104 <= nums[i] <= 3 * 104

  • Each element in the array appears twice except for one element which appears only once.

Deep-Dive & Conceptual Insights

Core Insight

XOR is associative and commutative. (2 ^ 2) ^ (1 ^ 1) ^ 4 = 0 ^ 0 ^ 4 = 4. Accumulating all elements with ^= requires zero extra memory and runs in a single linear scan.

Real-World Scenario & Production Applications

Duplicate detection in streaming telemetry without hash table allocation, parity RAID memory striping, fault isolation in mirrored storage registers.

Step-by-Step Execution Trace Table

IndexElement nums[i]BinaryAccumulator res (Before ^)OperationAccumulator res (After ^)
04100₂0 (000₂)0 ^ 44 (100₂)
11001₂4 (100₂)4 ^ 15 (101₂)
22010₂5 (101₂)5 ^ 27 (111₂)
31001₂7 (111₂)7 ^ 16 (110₂)
42010₂6 (110₂)6 ^ 24 (100₂)
Worked on Paper

The Math, Step by Step

1. The operation the code uses

XOR, written ⊕\oplus⊕ in math and ^ in Python, compares two numbers bit by bit. Each bit of the result is 1 when the two input bits differ, and 0 when they are equal.

Bit of aaaBit of bbbBit of a⊕ba \oplus ba⊕b
000
011
101
110

The code starts with res = 0 and XORs every element into it. So at the end, res holds nums[0]⊕nums[1]⊕⋯⊕nums[n−1]\text{nums}[0] \oplus \text{nums}[1] \oplus \cdots \oplus \text{nums}[n - 1]nums[0]⊕nums[1]⊕⋯⊕nums[n−1].

2. The three rules that leave only the single value

Each rule follows from the table, one bit position at a time.

  • A value XOR itself is 0: a⊕a=0a \oplus a = 0a⊕a=0. In every bit position the two bits are equal, so every result bit is 0.
  • A value XOR 0 is the value: a⊕0=aa \oplus 0 = aa⊕0=a. A bit XOR 0 keeps the bit.
  • Order does not matter: a⊕b=b⊕aa \oplus b = b \oplus aa⊕b=b⊕a, and (a⊕b)⊕c=a⊕(b⊕c)(a \oplus b) \oplus c = a \oplus (b \oplus c)(a⊕b)⊕c=a⊕(b⊕c). In one bit position, the result bit is 1 exactly when an odd number of the input bits are 1. That count does not depend on the order of the inputs.
3. Why only the single value survives

By the third rule, the code may be read as if the equal values stood next to each other. Say the values that appear twice are p1,p2,…p_1, p_2, \ldotsp1​,p2​,…, and the single value is sss. Then

res=(p1⊕p1)⊕(p2⊕p2)⊕⋯⊕s=0⊕0⊕⋯⊕s=s\text{res} = (p_1 \oplus p_1) \oplus (p_2 \oplus p_2) \oplus \cdots \oplus s = 0 \oplus 0 \oplus \cdots \oplus s = sres=(p1​⊕p1​)⊕(p2​⊕p2​)⊕⋯⊕s=0⊕0⊕⋯⊕s=s

The pairs become 0 by the first rule, and the 0s leave sss unchanged by the second rule. The code never groups the pairs itself. The third rule guarantees that the result is the same in any order.

4. Negative numbers and zero

The proof never uses the sign or the size of a value, only the rules of part 2. Python's ^ treats a negative number as its two's complement bits, with the sign bit repeated to the left without end. The three rules hold in every bit position, including the sign bits. So a single negative value is returned as itself. A single value of 0 also works: all pairs cancel to 0, and 0⊕0=00 \oplus 0 = 00⊕0=0.

The start value res = 0 is the second rule in use. Before the loop, res holds the XOR of no elements, which must leave the first element unchanged.

5. Example 2 by hand

nums = [4,1,2,1,2]. The table shows each value in 3-bit binary.

numnum in binaryres after res ^= numres in binary
41004100
10015101
20107111
10016110
20104100

The second 1 clears the bit that the first 1 set. The second 2 clears the bit that the first 2 set. Only the bit of 4 is left, so the code returns 4, the expected output. The two 1s were not next to each other in nums, and they still cancelled, as the third rule says.

6. Example 1 by hand

nums = [2,2,1]. In binary, 2 is 10 and 1 is 01. After the first 2, res is 10. After the second 2, res is 10 ⊕\oplus⊕ 10 === 00. After the 1, res is 00 ⊕\oplus⊕ 01 === 01, which is 1. The code returns 1, the expected output.

7. From the rules to the code
RuleIn singleNumber
start from the XOR of no elements, 000res = 0
XOR every element in, in any orderfor num in nums: with res ^= num
pairs give 000, and 0⊕s=s0 \oplus s = s0⊕s=sreturn res

The loop does one XOR per element, so it takes O(n)O(n)O(n) time. It keeps one integer, res, so it uses O(1)O(1)O(1) extra space.

Code Shape
Archetype Code Shape
Python
1res = 0
2for num in nums:
3 res ^= num
4return res

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

res ^= num cancels every duplicate while the loop runs, and at first it is not clear why. A physical picture shows the mechanism step by step.

🎴 The Analogy: Removing Matched Card Pairs

Imagine a deck where every card has an exact duplicate somewhere else in the deck, except one unmatched card. You flip through the deck once, and every time you've already seen a card's twin, you remove both cards of that pair from your hand. Whatever single card is left in your hand at the end must be the unmatched one, because no other card in the deck matched it.

🔑 Why It Works

XOR does exactly this, automatically, one card at a time:

  • Trick 1 — Empty hand: res = 0 is your hand before you've flipped anything. 0 ^ x = x, so the very first card you flip just goes straight into your hand.
  • Trick 2 — Pairs cancel, order doesn't matter: res ^= num for every card. Because x ^ x = 0, the moment a card's twin shows up (no matter how far apart the two copies are in the deck), they cancel each other to nothing. XOR is commutative and associative, so it doesn't matter what order the pairs appear in — every pair still cancels to 0.
  • Allocating hash set or sorting: Using a set consumes O(N)O(N)O(N) auxiliary space, and sorting takes O(Nlog⁡N)O(N \log N)O(NlogN) time. XOR involution property (x⊕x=0x \oplus x = 0x⊕x=0 and x⊕0=xx \oplus 0 = xx⊕0=x) solves the problem in O(N)O(N)O(N) time and O(1)O(1)O(1) space.

  • Leaving n out of the XOR: enumerate only supplies the indices 0..n-1, so n itself must be XORed in too; res = len(nums) does that. Starting at res = 0 misses it: [0, 1] returns 0 instead of 2.

  • Operator precedence in XOR expressions: In expressions like res ^ x + 1, addition has higher precedence than XOR (+ precedes ^), evaluating res ^ (x + 1).

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Array where every element appears twice except one unique element, O(1) space requirement.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: after each res ^= num, res is the XOR of the numbers seen so far, so every value seen twice has already cancelled and only the unpaired value can remain at the end.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Allocating a hash set or frequency map: Violates the strict O(1) extra space constraint.

  • Starting at res = nums[0] while for num in nums still visits nums[0] XORs it in twice: [4, 1, 2, 1, 2] returns 0 instead of 4.

The 60-Second Interview Pitch

Say this out loud before you type a single line

I'd use XOR Cancel. Every number in nums appears twice except one, and I need linear time and constant extra space, so I can't keep a set of the numbers I've seen. Instead I keep one integer, res, and fold every number into it with res ^= num. That works because a value XORed with itself is zero, a value XORed with zero is unchanged, and the order of the XORs doesn't matter: each pair cancels wherever its two copies sit, and only the unpaired number is left in res. The trap is the starting value. I start res at zero, because zero changes nothing; if I started at nums[0] and still looped over every number, nums[0] would be XORed in twice and cancel itself. One pass is O(N) time, and one integer is O(1) space.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at the execution steps: the loop for num in nums runs once per element and does one res ^= num each time. Single linear pass.

SPACE COMPLEXITY

O(1) Auxiliary

Look at memory allocations: Call stack uses O(1) Iterative. Single integer accumulator variable res in CPU register.

Formal Recurrence Relation

T(N) = ∑_{i=1}^N O(1) = O(N)

Derivation Progression

Loop Count

for num in nums → N iterations

The loop visits each of the N numbers exactly once.

Work per Iteration

res ^= num → O(1)

One XOR on one integer, the same cost for every element.

Linear Convergence

N operations = O(N)

Zero heap allocations or hash map lookups.

Variable Definitions

NNN

Total number of elements in the array

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(1) Single integer register

🟢 Output Space

O(1) Unique element 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 structural trigger is: all values come in pairs except one; return the unpaired value in linear time and constant extra space. The moment I see "everything is paired except one value," a hash set or frequency map is instantly disqualified because of the O(1)O(1)O(1) auxiliary space constraint, and XOR Cancel is the fit. At scale the same signal reads "find the odd one out in a stream too large to store": one running XOR needs no memory per element.

CONSTRAINTS & BOUNDS

N≤3×104N \le 3 \times 10^4N≤3×104, elements fit in 32-bit signed integers. An O(N)O(N)O(N) single pass is required. Bounds are simply the array bounds [0,N−1][0, N-1][0,N−1]. Because every duplicate appears exactly twice, accumulating the entire array into a single accumulator guarantees that all duplicate pairs cancel out to 000, leaving only the singleton.

FAANG PRODUCTION TRAPS & EDGE CASES

The primary trap is attempting to sort the array first, which costs O(Nlog⁡N)O(N \log N)O(NlogN) and violates the linear time requirement. Another trap is using this pattern when duplicates appear an odd number of times (e.g. 3 times), where XOR cancellation fails. Edge cases include single-element array nums = [x] (returns x in 1 step).

Core Algorithmic State Invariants

  1. Mergeable State

Because the whole state is one integer, two partial results combine with one more XOR: split nums into chunks, XOR each chunk, then XOR the chunk results. The answer is the same as one pass.

Theory Context•Bit Manipulation
EasyLC 136

Single Number (LeetCode 136)

Target Frequency:GoogleMetaAmazon

You're given a non-empty array of integers nums where every value shows up twice except for exactly one value that shows up only once. Return that lone value.

Your solution must run in linear time and use only constant extra space — no sorting, no hash map.

Worked Examples

Example 1
Input:nums = [2,2,1]
Output:1
Explanation: 2 appears twice; 1 appears once.
Example 2
Input:nums = [4,1,2,1,2]
Output:4
Explanation: 1 and 2 each appear twice; 4 appears once.
Example 3
Input:nums = [1]
Output:1
Explanation: The only element is the answer.

⚖️Formal Constraints & Bounds

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

  • -3 * 104 <= nums[i] <= 3 * 104

  • Each element in the array appears twice except for one element which appears only once.

Deep-Dive & Conceptual Insights

Core Insight

XOR is associative and commutative. (2 ^ 2) ^ (1 ^ 1) ^ 4 = 0 ^ 0 ^ 4 = 4. Accumulating all elements with ^= requires zero extra memory and runs in a single linear scan.

Real-World Scenario & Production Applications

Duplicate detection in streaming telemetry without hash table allocation, parity RAID memory striping, fault isolation in mirrored storage registers.

Step-by-Step Execution Trace Table

IndexElement nums[i]BinaryAccumulator res (Before ^)OperationAccumulator res (After ^)
04100₂0 (000₂)0 ^ 44 (100₂)
11001₂4 (100₂)4 ^ 15 (101₂)
22010₂5 (101₂)5 ^ 27 (111₂)
31001₂7 (111₂)7 ^ 16 (110₂)
42010₂6 (110₂)6 ^ 24 (100₂)
Worked on Paper

The Math, Step by Step

1. The operation the code uses

XOR, written ⊕\oplus⊕ in math and ^ in Python, compares two numbers bit by bit. Each bit of the result is 1 when the two input bits differ, and 0 when they are equal.

Bit of aaaBit of bbbBit of a⊕ba \oplus ba⊕b
000
011
101
110

The code starts with res = 0 and XORs every element into it. So at the end, res holds nums[0]⊕nums[1]⊕⋯⊕nums[n−1]\text{nums}[0] \oplus \text{nums}[1] \oplus \cdots \oplus \text{nums}[n - 1]nums[0]⊕nums[1]⊕⋯⊕nums[n−1].

2. The three rules that leave only the single value

Each rule follows from the table, one bit position at a time.

  • A value XOR itself is 0: a⊕a=0a \oplus a = 0a⊕a=0. In every bit position the two bits are equal, so every result bit is 0.
  • A value XOR 0 is the value: a⊕0=aa \oplus 0 = aa⊕0=a. A bit XOR 0 keeps the bit.
  • Order does not matter: a⊕b=b⊕aa \oplus b = b \oplus aa⊕b=b⊕a, and (a⊕b)⊕c=a⊕(b⊕c)(a \oplus b) \oplus c = a \oplus (b \oplus c)(a⊕b)⊕c=a⊕(b⊕c). In one bit position, the result bit is 1 exactly when an odd number of the input bits are 1. That count does not depend on the order of the inputs.
3. Why only the single value survives

By the third rule, the code may be read as if the equal values stood next to each other. Say the values that appear twice are p1,p2,…p_1, p_2, \ldotsp1​,p2​,…, and the single value is sss. Then

res=(p1⊕p1)⊕(p2⊕p2)⊕⋯⊕s=0⊕0⊕⋯⊕s=s\text{res} = (p_1 \oplus p_1) \oplus (p_2 \oplus p_2) \oplus \cdots \oplus s = 0 \oplus 0 \oplus \cdots \oplus s = sres=(p1​⊕p1​)⊕(p2​⊕p2​)⊕⋯⊕s=0⊕0⊕⋯⊕s=s

The pairs become 0 by the first rule, and the 0s leave sss unchanged by the second rule. The code never groups the pairs itself. The third rule guarantees that the result is the same in any order.

4. Negative numbers and zero

The proof never uses the sign or the size of a value, only the rules of part 2. Python's ^ treats a negative number as its two's complement bits, with the sign bit repeated to the left without end. The three rules hold in every bit position, including the sign bits. So a single negative value is returned as itself. A single value of 0 also works: all pairs cancel to 0, and 0⊕0=00 \oplus 0 = 00⊕0=0.

The start value res = 0 is the second rule in use. Before the loop, res holds the XOR of no elements, which must leave the first element unchanged.

5. Example 2 by hand

nums = [4,1,2,1,2]. The table shows each value in 3-bit binary.

numnum in binaryres after res ^= numres in binary
41004100
10015101
20107111
10016110
20104100

The second 1 clears the bit that the first 1 set. The second 2 clears the bit that the first 2 set. Only the bit of 4 is left, so the code returns 4, the expected output. The two 1s were not next to each other in nums, and they still cancelled, as the third rule says.

6. Example 1 by hand

nums = [2,2,1]. In binary, 2 is 10 and 1 is 01. After the first 2, res is 10. After the second 2, res is 10 ⊕\oplus⊕ 10 === 00. After the 1, res is 00 ⊕\oplus⊕ 01 === 01, which is 1. The code returns 1, the expected output.

7. From the rules to the code
RuleIn singleNumber
start from the XOR of no elements, 000res = 0
XOR every element in, in any orderfor num in nums: with res ^= num
pairs give 000, and 0⊕s=s0 \oplus s = s0⊕s=sreturn res

The loop does one XOR per element, so it takes O(n)O(n)O(n) time. It keeps one integer, res, so it uses O(1)O(1)O(1) extra space.

Code Shape
Archetype Code Shape
Python
1res = 0
2for num in nums:
3 res ^= num
4return res

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

res ^= num cancels every duplicate while the loop runs, and at first it is not clear why. A physical picture shows the mechanism step by step.

🎴 The Analogy: Removing Matched Card Pairs

Imagine a deck where every card has an exact duplicate somewhere else in the deck, except one unmatched card. You flip through the deck once, and every time you've already seen a card's twin, you remove both cards of that pair from your hand. Whatever single card is left in your hand at the end must be the unmatched one, because no other card in the deck matched it.

🔑 Why It Works

XOR does exactly this, automatically, one card at a time:

  • Trick 1 — Empty hand: res = 0 is your hand before you've flipped anything. 0 ^ x = x, so the very first card you flip just goes straight into your hand.
  • Trick 2 — Pairs cancel, order doesn't matter: res ^= num for every card. Because x ^ x = 0, the moment a card's twin shows up (no matter how far apart the two copies are in the deck), they cancel each other to nothing. XOR is commutative and associative, so it doesn't matter what order the pairs appear in — every pair still cancels to 0.
  • Allocating hash set or sorting: Using a set consumes O(N)O(N)O(N) auxiliary space, and sorting takes O(Nlog⁡N)O(N \log N)O(NlogN) time. XOR involution property (x⊕x=0x \oplus x = 0x⊕x=0 and x⊕0=xx \oplus 0 = xx⊕0=x) solves the problem in O(N)O(N)O(N) time and O(1)O(1)O(1) space.

  • Leaving n out of the XOR: enumerate only supplies the indices 0..n-1, so n itself must be XORed in too; res = len(nums) does that. Starting at res = 0 misses it: [0, 1] returns 0 instead of 2.

  • Operator precedence in XOR expressions: In expressions like res ^ x + 1, addition has higher precedence than XOR (+ precedes ^), evaluating res ^ (x + 1).

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Array where every element appears twice except one unique element, O(1) space requirement.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: after each res ^= num, res is the XOR of the numbers seen so far, so every value seen twice has already cancelled and only the unpaired value can remain at the end.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Allocating a hash set or frequency map: Violates the strict O(1) extra space constraint.

  • Starting at res = nums[0] while for num in nums still visits nums[0] XORs it in twice: [4, 1, 2, 1, 2] returns 0 instead of 4.

The 60-Second Interview Pitch

Say this out loud before you type a single line

I'd use XOR Cancel. Every number in nums appears twice except one, and I need linear time and constant extra space, so I can't keep a set of the numbers I've seen. Instead I keep one integer, res, and fold every number into it with res ^= num. That works because a value XORed with itself is zero, a value XORed with zero is unchanged, and the order of the XORs doesn't matter: each pair cancels wherever its two copies sit, and only the unpaired number is left in res. The trap is the starting value. I start res at zero, because zero changes nothing; if I started at nums[0] and still looped over every number, nums[0] would be XORed in twice and cancel itself. One pass is O(N) time, and one integer is O(1) space.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at the execution steps: the loop for num in nums runs once per element and does one res ^= num each time. Single linear pass.

SPACE COMPLEXITY

O(1) Auxiliary

Look at memory allocations: Call stack uses O(1) Iterative. Single integer accumulator variable res in CPU register.

Formal Recurrence Relation

T(N) = ∑_{i=1}^N O(1) = O(N)

Derivation Progression

Loop Count

for num in nums → N iterations

The loop visits each of the N numbers exactly once.

Work per Iteration

res ^= num → O(1)

One XOR on one integer, the same cost for every element.

Linear Convergence

N operations = O(N)

Zero heap allocations or hash map lookups.

Variable Definitions

NNN

Total number of elements in the array

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(1) Single integer register

🟢 Output Space

O(1) Unique element 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 structural trigger is: all values come in pairs except one; return the unpaired value in linear time and constant extra space. The moment I see "everything is paired except one value," a hash set or frequency map is instantly disqualified because of the O(1)O(1)O(1) auxiliary space constraint, and XOR Cancel is the fit. At scale the same signal reads "find the odd one out in a stream too large to store": one running XOR needs no memory per element.

CONSTRAINTS & BOUNDS

N≤3×104N \le 3 \times 10^4N≤3×104, elements fit in 32-bit signed integers. An O(N)O(N)O(N) single pass is required. Bounds are simply the array bounds [0,N−1][0, N-1][0,N−1]. Because every duplicate appears exactly twice, accumulating the entire array into a single accumulator guarantees that all duplicate pairs cancel out to 000, leaving only the singleton.

FAANG PRODUCTION TRAPS & EDGE CASES

The primary trap is attempting to sort the array first, which costs O(Nlog⁡N)O(N \log N)O(NlogN) and violates the linear time requirement. Another trap is using this pattern when duplicates appear an odd number of times (e.g. 3 times), where XOR cancellation fails. Edge cases include single-element array nums = [x] (returns x in 1 step).

Core Algorithmic State Invariants

  1. Mergeable State

Because the whole state is one integer, two partial results combine with one more XOR: split nums into chunks, XOR each chunk, then XOR the chunk results. The answer is the same as one pass.

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