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 89

Gray Code (LeetCode 89)

You get a number of bits, n. Build a list that holds every whole number from 0 to 2 ** n - 1 exactly once.

The list must follow three rules. It starts with 0. Each number and the number after it have binary forms that differ in exactly one place. The last number and the first number, 0, also differ in exactly one place.

Many lists follow these rules. Return any one of them.

Worked Examples

Example 1
Input:n = 2
Output:[0,1,3,2]
Explanation: In binary the list is 00, 01, 11, 10. 00 to 01 changes the last place. 01 to 11 changes the first place. 11 to 10 changes the last place. 10 back to 00 changes the first place. The list [0,2,3,1] follows the rules too.
Example 2
Input:n = 1
Output:[0,1]
Explanation: 0 and 1 differ in their only place. The last number 1 is also one place away from the first number 0.

⚖️Formal Constraints & Bounds

  • 1 <= n <= 16

  • Any list that follows the rules is accepted

Deep-Dive & Conceptual Insights

Core Insight

Bit k of the code i ^ (i >> 1) is 1 exactly when bits k and k + 1 of i differ. Counting from i to i + 1 flips bits 0 to t, where t is the number of 1 bits at the low end of i. A pair of places inside that range flips both of its bits, so the pair keeps its answer. Only the pair at places t and t + 1 changes, so the code changes in exactly one bit, and the last code 100...0 is one bit from the first code 0.

Real-World Scenario & Production Applications

A rotary encoder reports the angle of a shaft as a binary number. With plain counting, some steps change several bits at once, such as 011 to 100. The sensors do not switch at exactly the same moment, so a reader can briefly see a wrong number such as 111. A Gray code changes one bit per step, so a reader sees either the old position or the new one.

Step-by-Step Execution Trace Table

Trace of n = 3: the loop runs for i from 0 to 7, and each row gives the code of position i.

ii in binaryi >> 1i ^ (i >> 1)codeplace that changed from the row above
00000000000none
10010000011place 0
20100010113place 1
30110010102place 0
41000101106place 2
51010101117place 0
61100111015place 1
71110111004place 0

The function returns [0, 1, 3, 2, 6, 7, 5, 4]. Every row changes exactly one place. The last code 100 and the first code 000 also differ in exactly one place.

Another way to build the same list is to reflect it. Take the list for n - 1 bits, write it again in reverse order, and set the new top bit on every number of the copy. The two lists meet at the same number, and only the new top bit changes there. For n = 2, [0, 1] reflected is [1, 0], and with bit 1 set it is [3, 2], which gives [0, 1, 3, 2].

Code Shape
Archetype Code Shape
Python
1codes = []
2for i in range(1 << n):
3 codes.append(i ^ (i >> 1))
4return codes

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

A Gray code is a list of all 2 ** n numbers of n bits in which every number differs from the next one in exactly one bit. Plain counting does not do this: going from 01 to 10 changes two bits. The code i ^ (i >> 1) fixes this. The shift i >> 1 puts bit k + 1 of i at place k, so bit k of the code is 1 exactly when bits k and k + 1 of i differ.

Counting from i to i + 1 flips bits 0 to t, where t is the number of 1 bits at the low end of i. A pair of neighbouring places inside that range flips both bits, so the pair keeps its answer. Only the pair at places t and t + 1 changes, because bit t flips and bit t + 1 does not. That is exactly one bit of the code.

There is a second way to build the same list: reflect it. Take the list for n - 1 bits, write it again in reverse order, and set the new top bit on every number of the copy. The two lists meet at the same number, so only the new top bit changes there. The formula needs no list and no reversal, so it is the one to remember.

➗ What Is Added To Bit Tricks

Bit Tricks moves the bits of one number to new places with shifts and masks. Here the number is combined with a shifted copy of itself by XOR, and a loop over all 2 ** n positions applies the same step to each one. The result is not one rearranged number but a whole list whose neighbours are one bit apart.

🔑 The Key Idea in the Code

Each code depends only on its own position i, so no code looks at the previous one. The one-bit rule between neighbours follows from the formula. The loop bound is 1 << n, because n is the number of bits and there are 2 ** n codes.

  • Using the forward code n ^ (n >> 1): that turns a position into its code. Here n is the code and the answer is its position, which is the opposite direction. For n = 6 it returns 5, where 4 is right.

  • Stopping before the last shift with while n > 1: the highest bit of n is never folded into position. For n = 1 it returns 0, where 1 is right.

  • Adding with += instead of XOR with ^=: the folded bits must cancel in pairs, and addition carries instead. For n = 3 it returns 4, where 2 is right.

  • Carrying out the moves one at a time: the answer for n = 109 is 756249599, so a loop that applies each move runs about that many times and is too slow.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

"Differ in exactly one place" for each number and the next one, and "also from the last number back to the first": the order of all 2 ** n numbers matters, and the neighbours are only one bit apart. A rule that depends only on the position i points to a formula that turns i into its code.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

After i rounds, codes holds the first i Gray codes, and each one differs from the code before it in exactly one bit. The code at position i is i ^ (i >> 1), and counting from i to i + 1 flips only the pair of places t and t + 1, where t is the number of 1 bits at the low end of i.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • A loop over range(n): n is the number of bits, so n = 3 returns 3 codes where 8 are needed. The loop bound is 1 << n.

  • A loop that starts at position 1: the list does not start with 0, and n = 2 returns [1, 3, 2].

  • | instead of ^: two positions get the same code, and n = 2 returns [0, 1, 3, 3].

The 60-Second Interview Pitch

Say this out loud before you type a single line

This is Gray Step. I give each position i the code i XOR i shifted right by one. The shift puts bit k plus one of i at place k, so bit k of the code is 1 exactly when two neighbouring bits of i differ. Counting from i to i plus one flips the low bits up to the first 0. Each pair of places inside that range flips both bits, so it keeps its answer. Only the pair at the top of the range changes, so the code changes in exactly one bit. The trap is the loop bound: the loop runs over 1 shifted left by n, which is two to the power n, not over n. For n equal to 3, the codes are 0, 1, 3, 2, 6, 7, 5, 4. The last code, 4, is one bit from 0. The loop runs two to the power n times with constant work in each round, so time is O of 2 to the n, which is the size of the output, and extra space is O of 1.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(2^n)

Look at the loop. range(1 << n) runs 2 ** n rounds. Each round does one right shift, one XOR and one append, which is constant work for numbers of at most 16 bits. Time is therefore O(2^n). This is also the number of values in the output, so no algorithm can return the list faster.

SPACE COMPLEXITY

O(1)

The code keeps the loop variable i and the list codes. codes is the output, with 2 ** n integers, and the output is not counted. The auxiliary space is O(1): i and one temporary value.

Formal Recurrence Relation

T=2n⋅O(1)=O(2n)T = 2^n \cdot O(1) = O(2^n)T=2n⋅O(1)=O(2n)

Derivation Progression

Rounds

2^n

range(1 << n) gives every position from 0 to 2^n - 1 once.

Work per round

3 = O(1)

One right shift, one XOR and one append.

Total

3⋅2n=O(2n)3 \cdot 2^n = O(2^n)3⋅2n=O(2n)

Rounds times a constant amount of work.

Variable Definitions

nnn

The number of bits, 1 to 16

iii

The position of a code in the list, from 0 to 2^n - 1

Memory Architecture & Bounds

🟣 Call Stack

O(1): a loop only, no recursion

🔵 Auxiliary Heap

O(1): the loop variable and one temporary value

🟢 Output Space

O(2^n): the list of 2^n codes

Boundary Best / Worst Cases

Best Case

O(2n)O(2^n)O(2n): the loop always runs 2^n rounds, even for n = 1.

Average Case

O(2n)O(2^n)O(2n).

Worst Case

O(2n)O(2^n)O(2n): 65536 rounds for n = 16.

Recurrence Tree Topology

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

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

The prompt asks for "a list of all 2 ** n numbers where each number differs from the next in exactly one bit". The order of the whole list matters, and the one-bit rule links only neighbours. A rule that depends only on the position i points to a formula: the code of position i is i ^ (i >> 1).

CONSTRAINTS & BOUNDS

1≤n≤161 \le n \le 161≤n≤16, so the list has at most 216=655362^{16} = 65536216=65536 numbers. The output itself has 2n2^n2n numbers, so time is Θ(2n)\Theta(2^n)Θ(2n) and no algorithm is faster. Auxiliary space is O(1)O(1)O(1), because each code is computed from its own position.

FAANG PRODUCTION TRAPS & EDGE CASES

A loop over range(n) returns n codes instead of 2 ** n: n = 3 returns [0, 1, 3]. A loop that starts at position 1 leaves out 0: n = 2 returns [1, 3, 2]. i | (i >> 1) repeats a code: n = 2 returns [0, 1, 3, 3]. i << 1 instead of i >> 1 gives [0, 3, 6, 5] for n = 2.

Theory Context•Bit Manipulation
MediumLC 89

Gray Code (LeetCode 89)

You get a number of bits, n. Build a list that holds every whole number from 0 to 2 ** n - 1 exactly once.

The list must follow three rules. It starts with 0. Each number and the number after it have binary forms that differ in exactly one place. The last number and the first number, 0, also differ in exactly one place.

Many lists follow these rules. Return any one of them.

Worked Examples

Example 1
Input:n = 2
Output:[0,1,3,2]
Explanation: In binary the list is 00, 01, 11, 10. 00 to 01 changes the last place. 01 to 11 changes the first place. 11 to 10 changes the last place. 10 back to 00 changes the first place. The list [0,2,3,1] follows the rules too.
Example 2
Input:n = 1
Output:[0,1]
Explanation: 0 and 1 differ in their only place. The last number 1 is also one place away from the first number 0.

⚖️Formal Constraints & Bounds

  • 1 <= n <= 16

  • Any list that follows the rules is accepted

Deep-Dive & Conceptual Insights

Core Insight

Bit k of the code i ^ (i >> 1) is 1 exactly when bits k and k + 1 of i differ. Counting from i to i + 1 flips bits 0 to t, where t is the number of 1 bits at the low end of i. A pair of places inside that range flips both of its bits, so the pair keeps its answer. Only the pair at places t and t + 1 changes, so the code changes in exactly one bit, and the last code 100...0 is one bit from the first code 0.

Real-World Scenario & Production Applications

A rotary encoder reports the angle of a shaft as a binary number. With plain counting, some steps change several bits at once, such as 011 to 100. The sensors do not switch at exactly the same moment, so a reader can briefly see a wrong number such as 111. A Gray code changes one bit per step, so a reader sees either the old position or the new one.

Step-by-Step Execution Trace Table

Trace of n = 3: the loop runs for i from 0 to 7, and each row gives the code of position i.

ii in binaryi >> 1i ^ (i >> 1)codeplace that changed from the row above
00000000000none
10010000011place 0
20100010113place 1
30110010102place 0
41000101106place 2
51010101117place 0
61100111015place 1
71110111004place 0

The function returns [0, 1, 3, 2, 6, 7, 5, 4]. Every row changes exactly one place. The last code 100 and the first code 000 also differ in exactly one place.

Another way to build the same list is to reflect it. Take the list for n - 1 bits, write it again in reverse order, and set the new top bit on every number of the copy. The two lists meet at the same number, and only the new top bit changes there. For n = 2, [0, 1] reflected is [1, 0], and with bit 1 set it is [3, 2], which gives [0, 1, 3, 2].

Code Shape
Archetype Code Shape
Python
1codes = []
2for i in range(1 << n):
3 codes.append(i ^ (i >> 1))
4return codes

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

A Gray code is a list of all 2 ** n numbers of n bits in which every number differs from the next one in exactly one bit. Plain counting does not do this: going from 01 to 10 changes two bits. The code i ^ (i >> 1) fixes this. The shift i >> 1 puts bit k + 1 of i at place k, so bit k of the code is 1 exactly when bits k and k + 1 of i differ.

Counting from i to i + 1 flips bits 0 to t, where t is the number of 1 bits at the low end of i. A pair of neighbouring places inside that range flips both bits, so the pair keeps its answer. Only the pair at places t and t + 1 changes, because bit t flips and bit t + 1 does not. That is exactly one bit of the code.

There is a second way to build the same list: reflect it. Take the list for n - 1 bits, write it again in reverse order, and set the new top bit on every number of the copy. The two lists meet at the same number, so only the new top bit changes there. The formula needs no list and no reversal, so it is the one to remember.

➗ What Is Added To Bit Tricks

Bit Tricks moves the bits of one number to new places with shifts and masks. Here the number is combined with a shifted copy of itself by XOR, and a loop over all 2 ** n positions applies the same step to each one. The result is not one rearranged number but a whole list whose neighbours are one bit apart.

🔑 The Key Idea in the Code

Each code depends only on its own position i, so no code looks at the previous one. The one-bit rule between neighbours follows from the formula. The loop bound is 1 << n, because n is the number of bits and there are 2 ** n codes.

  • Using the forward code n ^ (n >> 1): that turns a position into its code. Here n is the code and the answer is its position, which is the opposite direction. For n = 6 it returns 5, where 4 is right.

  • Stopping before the last shift with while n > 1: the highest bit of n is never folded into position. For n = 1 it returns 0, where 1 is right.

  • Adding with += instead of XOR with ^=: the folded bits must cancel in pairs, and addition carries instead. For n = 3 it returns 4, where 2 is right.

  • Carrying out the moves one at a time: the answer for n = 109 is 756249599, so a loop that applies each move runs about that many times and is too slow.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

"Differ in exactly one place" for each number and the next one, and "also from the last number back to the first": the order of all 2 ** n numbers matters, and the neighbours are only one bit apart. A rule that depends only on the position i points to a formula that turns i into its code.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

After i rounds, codes holds the first i Gray codes, and each one differs from the code before it in exactly one bit. The code at position i is i ^ (i >> 1), and counting from i to i + 1 flips only the pair of places t and t + 1, where t is the number of 1 bits at the low end of i.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • A loop over range(n): n is the number of bits, so n = 3 returns 3 codes where 8 are needed. The loop bound is 1 << n.

  • A loop that starts at position 1: the list does not start with 0, and n = 2 returns [1, 3, 2].

  • | instead of ^: two positions get the same code, and n = 2 returns [0, 1, 3, 3].

The 60-Second Interview Pitch

Say this out loud before you type a single line

This is Gray Step. I give each position i the code i XOR i shifted right by one. The shift puts bit k plus one of i at place k, so bit k of the code is 1 exactly when two neighbouring bits of i differ. Counting from i to i plus one flips the low bits up to the first 0. Each pair of places inside that range flips both bits, so it keeps its answer. Only the pair at the top of the range changes, so the code changes in exactly one bit. The trap is the loop bound: the loop runs over 1 shifted left by n, which is two to the power n, not over n. For n equal to 3, the codes are 0, 1, 3, 2, 6, 7, 5, 4. The last code, 4, is one bit from 0. The loop runs two to the power n times with constant work in each round, so time is O of 2 to the n, which is the size of the output, and extra space is O of 1.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(2^n)

Look at the loop. range(1 << n) runs 2 ** n rounds. Each round does one right shift, one XOR and one append, which is constant work for numbers of at most 16 bits. Time is therefore O(2^n). This is also the number of values in the output, so no algorithm can return the list faster.

SPACE COMPLEXITY

O(1)

The code keeps the loop variable i and the list codes. codes is the output, with 2 ** n integers, and the output is not counted. The auxiliary space is O(1): i and one temporary value.

Formal Recurrence Relation

T=2n⋅O(1)=O(2n)T = 2^n \cdot O(1) = O(2^n)T=2n⋅O(1)=O(2n)

Derivation Progression

Rounds

2^n

range(1 << n) gives every position from 0 to 2^n - 1 once.

Work per round

3 = O(1)

One right shift, one XOR and one append.

Total

3⋅2n=O(2n)3 \cdot 2^n = O(2^n)3⋅2n=O(2n)

Rounds times a constant amount of work.

Variable Definitions

nnn

The number of bits, 1 to 16

iii

The position of a code in the list, from 0 to 2^n - 1

Memory Architecture & Bounds

🟣 Call Stack

O(1): a loop only, no recursion

🔵 Auxiliary Heap

O(1): the loop variable and one temporary value

🟢 Output Space

O(2^n): the list of 2^n codes

Boundary Best / Worst Cases

Best Case

O(2n)O(2^n)O(2n): the loop always runs 2^n rounds, even for n = 1.

Average Case

O(2n)O(2^n)O(2n).

Worst Case

O(2n)O(2^n)O(2n): 65536 rounds for n = 16.

Recurrence Tree Topology

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

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

The prompt asks for "a list of all 2 ** n numbers where each number differs from the next in exactly one bit". The order of the whole list matters, and the one-bit rule links only neighbours. A rule that depends only on the position i points to a formula: the code of position i is i ^ (i >> 1).

CONSTRAINTS & BOUNDS

1≤n≤161 \le n \le 161≤n≤16, so the list has at most 216=655362^{16} = 65536216=65536 numbers. The output itself has 2n2^n2n numbers, so time is Θ(2n)\Theta(2^n)Θ(2n) and no algorithm is faster. Auxiliary space is O(1)O(1)O(1), because each code is computed from its own position.

FAANG PRODUCTION TRAPS & EDGE CASES

A loop over range(n) returns n codes instead of 2 ** n: n = 3 returns [0, 1, 3]. A loop that starts at position 1 leaves out 0: n = 2 returns [1, 3, 2]. i | (i >> 1) repeats a code: n = 2 returns [0, 1, 3, 3]. i << 1 instead of i >> 1 gives [0, 3, 6, 5] for n = 2.

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