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 421

Maximum XOR of Two Numbers in an Array (LeetCode 421)

Target Frequency:GoogleAmazonMicrosoft

Given an integer array nums, find the largest value obtainable by XOR-ing any two elements nums[i] and nums[j] (the same index may be reused, i.e. 0 <= i <= j < n).

Worked Examples

Example 1
Input:nums = [3,10,5,25,2,8]
Output:28
Explanation: The maximum result is 5 XOR 25 = 28.
Example 2
Input:nums = [14,70,53,83,49,91,36,80,92,51,66,70]
Output:127
Explanation: 91 XOR 36 = 127, and no other pair does better.

⚖️Formal Constraints & Bounds

  • 1 <= nums.length <= 2 * 105

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

Deep-Dive & Conceptual Insights

Core Insight

Build the answer bit-by-bit from the most significant bit down. At each bit position, greedily assume the answer can have that bit set, then verify by checking whether two numbers' prefixes-so-far actually XOR to that candidate (via a hash set of prefixes or a walked bit-trie). A greedy bet that isn't provably achievable is simply skipped, so the final result is guaranteed maximal in O(32*N) time.

Real-World Scenario & Production Applications

Finding the two most dissimilar hash fingerprints in a deduplication index, maximizing Hamming distance between error-correcting codewords, and IP-routing longest-prefix-divergence lookups.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Greedy Bit-by-Bit MSB-to-LSB Construction

Build the answer one bit position at a time, from the most significant bit (31) down to the least significant bit (0), growing a mask that exposes longer and longer prefixes of every number.

Mathematical Recurrence / Code Invariant
max_xor, mask = 0, 0
for i in range(31, -1, -1):
    mask |= (1 << i)

Step-by-Step Execution Trace Table

Worked trace: nums = [3, 10, 5, 25, 2, 8]
Bit imaskPrefix set (masked nums)candidate = max_xor \vert (1<<i)Verified?max_xor after
410000 (16){0, 16}16Yes (0 ^ 16 = 16)16
311000 (24){0, 8, 24}24Yes (0 ^ 24 = 24)24
211100 (28){0, 4, 8, 24}28Yes (4 ^ 24 = 28)28
111110 (30){2, 4, 8, 10, 24}30No28
011111 (31){2, 3, 5, 8, 10, 25}29No28

Final max_xor = 28, achieved by 5 XOR 25 = 00101 ^ 11001 = 11100 = 28, matching the expected output.

Code Shape
Archetype Code Shape
Python
1max_xor, mask = 0, 0
2for i in range(31, -1, -1):
3 mask |= (1 << i)
4 prefixes = {num & mask for num in nums}
5 candidate = max_xor | (1 << i)
6 for p in prefixes:
7 if (candidate ^ p) in prefixes:
8 max_xor = candidate
9 break
10return max_xor

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

Every earlier bit-manipulation archetype processed ALL 32 bits of ONE number at a time. This archetype reverses that: it processes ONE bit position at a time, across ALL numbers at once, building the answer from its most significant bit down to its least significant bit — greedily locking in every bit it can prove is achievable.

🏔️ The Analogy: Building the Tallest Answer One Floor at a Time, Verified Before You Commit

Imagine constructing a skyscraper's blueprint one floor at a time, starting from the top (bit 31) down to the ground floor (bit 0). At each floor, you ask a greedy question: "Can I add a floor here and still have this building be physically buildable with the materials (numbers) I have?" You never build a floor speculatively and tear it down later — you only ever add a floor once you've proven two of your numbers share every floor built so far except this one, where they differ.

  • Trick 1 — Growing prefixes (mask |= (1 << i)): The mask exposes just the top (32 - i) bits of every number — everything built "so far", floor by floor.
  • Trick 2 — Prefix set (prefixes = {num & mask for num in nums}): Recompute every number's current prefix under the new, slightly-longer mask.
  • Trick 3 — The greedy bet (candidate = max_xor | (1 << i)): Assume you CAN set this floor's bit to 1 in the final answer.
  • Trick 4 — Verify with the XOR-inverse trick ((candidate ^ p) in prefixes): If some prefix p is in the set, and candidate ^ p is ALSO in the set, then those two prefixes XOR together to exactly candidate — the bet is provably achievable, so max_xor permanently locks in that bit. If no such pair exists, the floor can't be built here, and max_xor keeps its bit at 0 for this position — never regressing, only growing.
🔑 The Key Idea in the Code

This is the hash-set version of a bit-trie walk: instead of building 32 levels of trie nodes and walking root-to-leaf per number, you replay the same greedy "does a complementary prefix exist" check using plain sets, in O(32·N) time and O(N) space.

  • Quadratic O(N2)O(N^2)O(N2) brute-force pair comparison: Comparing every pair of numbers takes O(N2)O(N^2)O(N2) time, which TLEs on N=2⋅105N = 2 \cdot 10^5N=2⋅105. A Binary Trie or prefix hash set greedy bit evaluation achieves O(31⋅N)=O(N)O(31 \cdot N) = O(N)O(31⋅N)=O(N) time.

  • Prefix set bit search property: At each bit position from bit 30 down to 0, test if a candidate maximum prefix can be formed: if candidate ^ p exists in the prefix set, p1 ^ p2 == candidate is guaranteed.

  • Iterating LSB to MSB instead of MSB to LSB: Greedy XOR maximization must make decisions from most significant bit (bit 30) down to least significant bit (bit 0), because a higher bit outweighs all lower bits combined.

  • Maximum XOR of Two Numbers — rebuilding the WHOLE prefix set every bit, not incrementally: the mask only ever grows (bits are added, never removed), so prefixes = {num & mask for num in nums} must be recomputed fresh each iteration from the ORIGINAL numbers, not from the previous iteration's already-masked prefixes — masking an already-masked value with a larger mask is a no-op and silently breaks the invariant.

  • Maximum XOR of Two Numbers — checking candidate in prefixes instead of the XOR-inverse: the verification step is NOT "is candidate itself a prefix" — it is "does some prefix p have its partner candidate ^ p also present". Checking membership of candidate directly (rather than candidate ^ p) looks superficially similar but never actually confirms two DIFFERENT numbers combine to the candidate value.

  • Maximum XOR of Two Numbers — pairing a number with itself: the loop bounds 0 <= i <= j < n technically allow i == j, but x XOR x = 0 is never the maximum unless every element is identical; a trie/hash-set implementation naturally handles this since a number's own prefix is always present in the set, but a hand-rolled O(N^2) baseline must remember not to special-case away legitimate i == j in a way that also breaks i != j pairs.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Maximum XOR of any pair in an array, O(N) or O(N log(max_value)) time requirement, N up to 2 * 10^5 ruling out O(N^2).

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: if two numbers' prefixes under the current mask differ only in the newly-exposed bit, their XOR of that prefix equals the greedy candidate, proving the bit is achievable.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Checking all O(N^2) pairs directly: too slow for N up to 2*10^5; must process bit positions, not pairs.

  • Forgetting that mask must grow monotonically (MSB to LSB) so earlier, more significant bit decisions are never revisited or invalidated by later ones.

  • Comparing full untruncated numbers rather than their masked prefixes, which breaks the greedy proof.

The 60-Second Interview Pitch

Say this out loud before you type a single line

"I build the answer bit-by-bit from bit 31 down to bit 0. At each position I grow a mask to expose one more bit of every number's prefix, collect those prefixes into a set, and greedily assume the answer's bit here can be 1. I verify by checking whether some prefix p in the set has its XOR-partner (candidate ^ p) also in the set -- if so the bit is provably achievable and I lock it in. This avoids ever comparing all pairs directly, running in O(32*N) = O(N) time and O(N) space. The same idea can be implemented as a walked bit-trie instead of a hash set."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at the execution steps: For each of the 32 bit positions, rebuild the prefix set (O(N)) and scan it once (O(N)) to verify the greedy bet. Total work is 32 * O(N) = O(32N), which is O(N) since 32 is a fixed constant.

SPACE COMPLEXITY

O(N) Auxiliary

Look at memory allocations: Call stack uses O(1) Iterative. Stores one prefix set of up to N integers per bit position (reused, not accumulated) in O(N) auxiliary space.

Formal Recurrence Relation

T(N) = 32 · O(N) = O(N)

Derivation Progression

Per-Bit Prefix Set Construction

prefixes={num&mask:num∈nums}prefixes = \{num \& mask : num \in nums\}prefixes={num&mask:num∈nums}

Rebuilding the prefix set for one bit position costs O(N).

Per-Bit Greedy Verification Scan

∃ p∈prefixes:(candidate⊕p)∈prefixes\exists\, p \in prefixes : (candidate \oplus p) \in prefixes∃p∈prefixes:(candidate⊕p)∈prefixes

Scanning the prefix set to verify the greedy bet costs O(N) per bit position.

Total Across 32 Bit Positions

32⋅O(N)=O(N)32 \cdot O(N) = O(N)32⋅O(N)=O(N)

32 is a fixed constant (not dependent on N), so total time remains linear in N.

Variable Definitions

NNN

Total number of elements in the array

323232

Fixed bit width of a 32-bit integer (constant, not a function of N)

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(N) One prefix set of up to N integers per bit position

🟢 Output Space

O(1) Single integer result

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 asks for the "maximum XOR of two numbers in an array in O(n) runtime." Comparing all pairs takes O(N2)O(N^2)O(N2), which TLEs for N=2×105N = 2 \times 10^5N=2×105. The key insight is that the most significant bit (MSB) dominates all lower bits combined: 2k>∑j=0k−12j2^k > \sum_{j=0}^{k-1} 2^j2k>∑j=0k−1​2j. Therefore, we can greedily determine the optimal XOR value bit-by-bit from MSB (bit 30) down to LSB (bit 0)!

CONSTRAINTS & BOUNDS

N≤2×105N \le 2 \times 10^5N≤2×105, values fit in 31 non-negative bits (0≤nums[i]≤231−10 \le \text{nums}[i] \le 2^{31} - 10≤nums[i]≤231−1). An O(31N)=O(N)O(31 N) = O(N)O(31N)=O(N) algorithm is required.

FAANG PRODUCTION TRAPS & EDGE CASES

The primary trap is scanning LSB to MSB; greedy choice only works MSB to LSB because a higher bit outweighs all lower bits. Another trap is rebuilding prefixes naively without masking: mask |= (1 << i) must accumulate prefixes from bit 30 down to iii.

Theory Context•Bit Manipulation
MediumLC 421

Maximum XOR of Two Numbers in an Array (LeetCode 421)

Target Frequency:GoogleAmazonMicrosoft

Given an integer array nums, find the largest value obtainable by XOR-ing any two elements nums[i] and nums[j] (the same index may be reused, i.e. 0 <= i <= j < n).

Worked Examples

Example 1
Input:nums = [3,10,5,25,2,8]
Output:28
Explanation: The maximum result is 5 XOR 25 = 28.
Example 2
Input:nums = [14,70,53,83,49,91,36,80,92,51,66,70]
Output:127
Explanation: 91 XOR 36 = 127, and no other pair does better.

⚖️Formal Constraints & Bounds

  • 1 <= nums.length <= 2 * 105

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

Deep-Dive & Conceptual Insights

Core Insight

Build the answer bit-by-bit from the most significant bit down. At each bit position, greedily assume the answer can have that bit set, then verify by checking whether two numbers' prefixes-so-far actually XOR to that candidate (via a hash set of prefixes or a walked bit-trie). A greedy bet that isn't provably achievable is simply skipped, so the final result is guaranteed maximal in O(32*N) time.

Real-World Scenario & Production Applications

Finding the two most dissimilar hash fingerprints in a deduplication index, maximizing Hamming distance between error-correcting codewords, and IP-routing longest-prefix-divergence lookups.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Greedy Bit-by-Bit MSB-to-LSB Construction

Build the answer one bit position at a time, from the most significant bit (31) down to the least significant bit (0), growing a mask that exposes longer and longer prefixes of every number.

Mathematical Recurrence / Code Invariant
max_xor, mask = 0, 0
for i in range(31, -1, -1):
    mask |= (1 << i)

Step-by-Step Execution Trace Table

Worked trace: nums = [3, 10, 5, 25, 2, 8]
Bit imaskPrefix set (masked nums)candidate = max_xor \vert (1<<i)Verified?max_xor after
410000 (16){0, 16}16Yes (0 ^ 16 = 16)16
311000 (24){0, 8, 24}24Yes (0 ^ 24 = 24)24
211100 (28){0, 4, 8, 24}28Yes (4 ^ 24 = 28)28
111110 (30){2, 4, 8, 10, 24}30No28
011111 (31){2, 3, 5, 8, 10, 25}29No28

Final max_xor = 28, achieved by 5 XOR 25 = 00101 ^ 11001 = 11100 = 28, matching the expected output.

Code Shape
Archetype Code Shape
Python
1max_xor, mask = 0, 0
2for i in range(31, -1, -1):
3 mask |= (1 << i)
4 prefixes = {num & mask for num in nums}
5 candidate = max_xor | (1 << i)
6 for p in prefixes:
7 if (candidate ^ p) in prefixes:
8 max_xor = candidate
9 break
10return max_xor

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

Every earlier bit-manipulation archetype processed ALL 32 bits of ONE number at a time. This archetype reverses that: it processes ONE bit position at a time, across ALL numbers at once, building the answer from its most significant bit down to its least significant bit — greedily locking in every bit it can prove is achievable.

🏔️ The Analogy: Building the Tallest Answer One Floor at a Time, Verified Before You Commit

Imagine constructing a skyscraper's blueprint one floor at a time, starting from the top (bit 31) down to the ground floor (bit 0). At each floor, you ask a greedy question: "Can I add a floor here and still have this building be physically buildable with the materials (numbers) I have?" You never build a floor speculatively and tear it down later — you only ever add a floor once you've proven two of your numbers share every floor built so far except this one, where they differ.

  • Trick 1 — Growing prefixes (mask |= (1 << i)): The mask exposes just the top (32 - i) bits of every number — everything built "so far", floor by floor.
  • Trick 2 — Prefix set (prefixes = {num & mask for num in nums}): Recompute every number's current prefix under the new, slightly-longer mask.
  • Trick 3 — The greedy bet (candidate = max_xor | (1 << i)): Assume you CAN set this floor's bit to 1 in the final answer.
  • Trick 4 — Verify with the XOR-inverse trick ((candidate ^ p) in prefixes): If some prefix p is in the set, and candidate ^ p is ALSO in the set, then those two prefixes XOR together to exactly candidate — the bet is provably achievable, so max_xor permanently locks in that bit. If no such pair exists, the floor can't be built here, and max_xor keeps its bit at 0 for this position — never regressing, only growing.
🔑 The Key Idea in the Code

This is the hash-set version of a bit-trie walk: instead of building 32 levels of trie nodes and walking root-to-leaf per number, you replay the same greedy "does a complementary prefix exist" check using plain sets, in O(32·N) time and O(N) space.

  • Quadratic O(N2)O(N^2)O(N2) brute-force pair comparison: Comparing every pair of numbers takes O(N2)O(N^2)O(N2) time, which TLEs on N=2⋅105N = 2 \cdot 10^5N=2⋅105. A Binary Trie or prefix hash set greedy bit evaluation achieves O(31⋅N)=O(N)O(31 \cdot N) = O(N)O(31⋅N)=O(N) time.

  • Prefix set bit search property: At each bit position from bit 30 down to 0, test if a candidate maximum prefix can be formed: if candidate ^ p exists in the prefix set, p1 ^ p2 == candidate is guaranteed.

  • Iterating LSB to MSB instead of MSB to LSB: Greedy XOR maximization must make decisions from most significant bit (bit 30) down to least significant bit (bit 0), because a higher bit outweighs all lower bits combined.

  • Maximum XOR of Two Numbers — rebuilding the WHOLE prefix set every bit, not incrementally: the mask only ever grows (bits are added, never removed), so prefixes = {num & mask for num in nums} must be recomputed fresh each iteration from the ORIGINAL numbers, not from the previous iteration's already-masked prefixes — masking an already-masked value with a larger mask is a no-op and silently breaks the invariant.

  • Maximum XOR of Two Numbers — checking candidate in prefixes instead of the XOR-inverse: the verification step is NOT "is candidate itself a prefix" — it is "does some prefix p have its partner candidate ^ p also present". Checking membership of candidate directly (rather than candidate ^ p) looks superficially similar but never actually confirms two DIFFERENT numbers combine to the candidate value.

  • Maximum XOR of Two Numbers — pairing a number with itself: the loop bounds 0 <= i <= j < n technically allow i == j, but x XOR x = 0 is never the maximum unless every element is identical; a trie/hash-set implementation naturally handles this since a number's own prefix is always present in the set, but a hand-rolled O(N^2) baseline must remember not to special-case away legitimate i == j in a way that also breaks i != j pairs.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Maximum XOR of any pair in an array, O(N) or O(N log(max_value)) time requirement, N up to 2 * 10^5 ruling out O(N^2).

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: if two numbers' prefixes under the current mask differ only in the newly-exposed bit, their XOR of that prefix equals the greedy candidate, proving the bit is achievable.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Checking all O(N^2) pairs directly: too slow for N up to 2*10^5; must process bit positions, not pairs.

  • Forgetting that mask must grow monotonically (MSB to LSB) so earlier, more significant bit decisions are never revisited or invalidated by later ones.

  • Comparing full untruncated numbers rather than their masked prefixes, which breaks the greedy proof.

The 60-Second Interview Pitch

Say this out loud before you type a single line

"I build the answer bit-by-bit from bit 31 down to bit 0. At each position I grow a mask to expose one more bit of every number's prefix, collect those prefixes into a set, and greedily assume the answer's bit here can be 1. I verify by checking whether some prefix p in the set has its XOR-partner (candidate ^ p) also in the set -- if so the bit is provably achievable and I lock it in. This avoids ever comparing all pairs directly, running in O(32*N) = O(N) time and O(N) space. The same idea can be implemented as a walked bit-trie instead of a hash set."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at the execution steps: For each of the 32 bit positions, rebuild the prefix set (O(N)) and scan it once (O(N)) to verify the greedy bet. Total work is 32 * O(N) = O(32N), which is O(N) since 32 is a fixed constant.

SPACE COMPLEXITY

O(N) Auxiliary

Look at memory allocations: Call stack uses O(1) Iterative. Stores one prefix set of up to N integers per bit position (reused, not accumulated) in O(N) auxiliary space.

Formal Recurrence Relation

T(N) = 32 · O(N) = O(N)

Derivation Progression

Per-Bit Prefix Set Construction

prefixes={num&mask:num∈nums}prefixes = \{num \& mask : num \in nums\}prefixes={num&mask:num∈nums}

Rebuilding the prefix set for one bit position costs O(N).

Per-Bit Greedy Verification Scan

∃ p∈prefixes:(candidate⊕p)∈prefixes\exists\, p \in prefixes : (candidate \oplus p) \in prefixes∃p∈prefixes:(candidate⊕p)∈prefixes

Scanning the prefix set to verify the greedy bet costs O(N) per bit position.

Total Across 32 Bit Positions

32⋅O(N)=O(N)32 \cdot O(N) = O(N)32⋅O(N)=O(N)

32 is a fixed constant (not dependent on N), so total time remains linear in N.

Variable Definitions

NNN

Total number of elements in the array

323232

Fixed bit width of a 32-bit integer (constant, not a function of N)

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(N) One prefix set of up to N integers per bit position

🟢 Output Space

O(1) Single integer result

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 asks for the "maximum XOR of two numbers in an array in O(n) runtime." Comparing all pairs takes O(N2)O(N^2)O(N2), which TLEs for N=2×105N = 2 \times 10^5N=2×105. The key insight is that the most significant bit (MSB) dominates all lower bits combined: 2k>∑j=0k−12j2^k > \sum_{j=0}^{k-1} 2^j2k>∑j=0k−1​2j. Therefore, we can greedily determine the optimal XOR value bit-by-bit from MSB (bit 30) down to LSB (bit 0)!

CONSTRAINTS & BOUNDS

N≤2×105N \le 2 \times 10^5N≤2×105, values fit in 31 non-negative bits (0≤nums[i]≤231−10 \le \text{nums}[i] \le 2^{31} - 10≤nums[i]≤231−1). An O(31N)=O(N)O(31 N) = O(N)O(31N)=O(N) algorithm is required.

FAANG PRODUCTION TRAPS & EDGE CASES

The primary trap is scanning LSB to MSB; greedy choice only works MSB to LSB because a higher bit outweighs all lower bits. Another trap is rebuilding prefixes naively without masking: mask |= (1 << i) must accumulate prefixes from bit 30 down to iii.

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