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 461

Swap Odd and Even Bits

Target Frequency:AmazonMetaNetflix

Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on).

Worked Examples

Example 1
Input:n = 23 (00010111₂)
Output:43 (00101011₂)
Explanation: Bits at (0,1), (2,3), (4,5) are paired and swapped.

⚖️Formal Constraints & Bounds

  • 0 <= n <= 232 - 1

Deep-Dive & Conceptual Insights

Core Insight

0xAAAAAAAA (10101010...) isolates all odd bits; right-shifting moves them to even positions. 0x55555555 (01010101...) isolates all even bits; left-shifting moves them to odd positions. Combining with OR ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1) solves the problem in O(1) instructions.

Real-World Scenario & Production Applications

Hardware bit interleaving/de-interleaving in radio communications, raster display pixel packing, cryptographic permutation S-box operations.

Step-by-Step Execution Trace Table

StepOperationBitmask UsedEffect on BitsBinary Transformation Example (n = 23 = 00010111_2)
1Extract Even Bits0xAAAAAAAAClears all odd positions00010111 & 10101010 = 00000010_2
2Shift Even Bits Right>> 1Moves even bits to odd positions00000010 >> 1 = 00000001_2
3Extract Odd Bits0x55555555Clears all even positions00010111 & 01010101 = 00010101_2
4Shift Odd Bits Left<< 1Moves odd bits to even positions00010101 << 1 = 00101010_2
5Combine ResultsBitwise OR \vertMerges odd and even swapped halves00000001 \vert 00101010 = 00101011_2 (43)
Code Shape
Archetype Code Shape
Python
1even_mask, odd_mask = 0xAAAAAAAA, 0x55555555
2return ((n & even_mask) >> 1) | ((n & odd_mask) << 1)

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

Two hex constants swapping bits in one line looks unreadable until you picture what each mask is physically doing.

🧦 The Analogy: Two Combs Pulling Apart a Zipper

Your bits alternate like a zipper: even-position, odd-position, even-position, odd-position... You can't swap neighbors in place directly, so instead you pull the zipper apart into two separate combs, then reassemble it flipped.

🔑 Why It Works
  • Trick 1 — Comb A (n & 0xAAAAAAAA): This mask has 1s at every even bit position, so ANDing with it keeps only those bits and zeroes everything else — it's a comb that grabs every other tooth.
  • Trick 2 — Comb B (n & 0x55555555): The complementary mask, grabbing exactly the interleaved teeth Comb A left behind.
  • Trick 3 — Sliding into place (>> 1 / << 1): Shift Comb A's teeth one slot right and Comb B's teeth one slot left — each comb now sits exactly where the other one used to be.
  • Trick 4 — Zipping back up (|): Since the two combs never overlap (each owns a disjoint set of bit positions), OR-ing them together zips the row back into one number, now with every neighbor pair swapped.
  • Using wrong 32-bit bitmasks: The even bitmask must be 0xAAAAAAAA (bits at positions 1, 3, 5...) and odd bitmask 0x55555555 (bits at positions 0, 2, 4...). Using transposed or 16-bit masks truncates high bits.

  • Shifting in the wrong direction: Even bits must shift right (>> 1) to land on odd positions, and odd bits must shift left (<< 1) to land on even positions.

  • Operator precedence without grouping: In (n & 0xAAAAAAAA) >> 1 | (n & 0x55555555) << 1, ensure parenthesis grouping around shifts and bitwise ANDs before bitwise OR.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Swap bits at even and odd index positions, pairwise bit transposition, constant instruction count.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: 0xAAAAAAAA (1010...) isolates all bits at odd positions; 0x55555555 (0101...) isolates all bits at even positions.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Sign-extension on odd-bit right shift: Shifting (n & 0xAAAAAAAA) right by 1 using signed >> can propagate the sign bit if the 31st bit is set. Use logical shift >>> or mask with 0x7FFFFFFF.

  • Hex mask typos: 0xAAAA is only 16 bits; a 32-bit integer requires 8 hex digits (0xAAAAAAAA and 0x55555555).

  • Iterating bit-by-bit: Looping 16 times with swaps is needlessly slow when two bitwise masks accomplish the swap in 3 CPU cycles.

The 60-Second Interview Pitch

Say this out loud before you type a single line

I isolate all odd bits using the mask 0xAAAAAAAA and shift them right by 1 into even positions. Concurrently, I isolate all even bits using 0x55555555 and shift them left by 1 into odd positions. Finally, I combine the two shifted values using bitwise OR. Runs in O(1) constant time with zero extra space.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(1)

Look at the execution steps: Masks even bits with 0xAAAAAAAA and shifts right by 1; masks odd bits with 0x55555555 and shifts left by 1; combines with bitwise OR: ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1). Runs in 3 CPU instructions.

SPACE COMPLEXITY

O(1) Auxiliary

Look at memory allocations: Call stack uses O(1). Single 32-bit integer in CPU register.

Formal Recurrence Relation

T=3 CPU instructions=O(1)T = 3 \text{ CPU instructions} = O(1)T=3 CPU instructions=O(1)

Derivation Progression

Even Bit Mask & Shift

(n \& 0xAAAAAAAA) >> 1

Extracts all even-positioned bits and shifts them to odd positions.

Odd Bit Mask & Shift

(n \& 0x55555555) << 1

Extracts all odd-positioned bits and shifts them to even positions.

Bitwise Recombination

even | odd

Combines swapped bits in single constant-time OR instruction.

Variable Definitions

323232

Fixed 32-bit word width (3 constant CPU register operations)

Memory Architecture & Bounds

🟣 Call Stack

O(1)

🔵 Auxiliary Heap

O(1) CPU register

🟢 Output Space

O(1) 32-bit integer

Boundary Best / Worst Cases

Best Case

O(1)O(1)O(1)

Average Case

O(1)O(1)O(1)

Worst Case

O(1)O(1)O(1)

Pointer Invariant Transition Progression

Pointer Invariant Transition Progression
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

The problem asks to "swap odd and even bits in an integer with as few operations as possible." Bit 0 and Bit 1 swap, Bit 2 and Bit 3 swap, etc. Iterating bit-by-bit is slow and unnecessary. The structural trigger is SIMD-style Whole-Word Masking: we isolate all even bits with an even-bit mask, isolate all odd bits with an odd-bit mask, shift each into their complementary positions, and recombine with bitwise OR.

CONSTRAINTS & BOUNDS

Input is a 32-bit integer. The even mask for bits 0, 2, 4... is 0x55555555 (...01010101). The odd mask for bits 1, 3, 5... is 0xAAAAAAAA (...10101010). Time complexity must be strictly O(1)O(1)O(1) using zero loops.

FAANG PRODUCTION TRAPS & EDGE CASES

In typed languages, shifting signed negative numbers right with >> propagates sign bits; an unsigned right shift >>> or casting to unsigned integer is necessary. In Python, large integers must be masked with 0xFFFFFFFF to simulate 32-bit unsigned boundaries.

Theory Context•Bit Manipulation
EasyLC 461

Swap Odd and Even Bits

Target Frequency:AmazonMetaNetflix

Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on).

Worked Examples

Example 1
Input:n = 23 (00010111₂)
Output:43 (00101011₂)
Explanation: Bits at (0,1), (2,3), (4,5) are paired and swapped.

⚖️Formal Constraints & Bounds

  • 0 <= n <= 232 - 1

Deep-Dive & Conceptual Insights

Core Insight

0xAAAAAAAA (10101010...) isolates all odd bits; right-shifting moves them to even positions. 0x55555555 (01010101...) isolates all even bits; left-shifting moves them to odd positions. Combining with OR ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1) solves the problem in O(1) instructions.

Real-World Scenario & Production Applications

Hardware bit interleaving/de-interleaving in radio communications, raster display pixel packing, cryptographic permutation S-box operations.

Step-by-Step Execution Trace Table

StepOperationBitmask UsedEffect on BitsBinary Transformation Example (n = 23 = 00010111_2)
1Extract Even Bits0xAAAAAAAAClears all odd positions00010111 & 10101010 = 00000010_2
2Shift Even Bits Right>> 1Moves even bits to odd positions00000010 >> 1 = 00000001_2
3Extract Odd Bits0x55555555Clears all even positions00010111 & 01010101 = 00010101_2
4Shift Odd Bits Left<< 1Moves odd bits to even positions00010101 << 1 = 00101010_2
5Combine ResultsBitwise OR \vertMerges odd and even swapped halves00000001 \vert 00101010 = 00101011_2 (43)
Code Shape
Archetype Code Shape
Python
1even_mask, odd_mask = 0xAAAAAAAA, 0x55555555
2return ((n & even_mask) >> 1) | ((n & odd_mask) << 1)

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

Two hex constants swapping bits in one line looks unreadable until you picture what each mask is physically doing.

🧦 The Analogy: Two Combs Pulling Apart a Zipper

Your bits alternate like a zipper: even-position, odd-position, even-position, odd-position... You can't swap neighbors in place directly, so instead you pull the zipper apart into two separate combs, then reassemble it flipped.

🔑 Why It Works
  • Trick 1 — Comb A (n & 0xAAAAAAAA): This mask has 1s at every even bit position, so ANDing with it keeps only those bits and zeroes everything else — it's a comb that grabs every other tooth.
  • Trick 2 — Comb B (n & 0x55555555): The complementary mask, grabbing exactly the interleaved teeth Comb A left behind.
  • Trick 3 — Sliding into place (>> 1 / << 1): Shift Comb A's teeth one slot right and Comb B's teeth one slot left — each comb now sits exactly where the other one used to be.
  • Trick 4 — Zipping back up (|): Since the two combs never overlap (each owns a disjoint set of bit positions), OR-ing them together zips the row back into one number, now with every neighbor pair swapped.
  • Using wrong 32-bit bitmasks: The even bitmask must be 0xAAAAAAAA (bits at positions 1, 3, 5...) and odd bitmask 0x55555555 (bits at positions 0, 2, 4...). Using transposed or 16-bit masks truncates high bits.

  • Shifting in the wrong direction: Even bits must shift right (>> 1) to land on odd positions, and odd bits must shift left (<< 1) to land on even positions.

  • Operator precedence without grouping: In (n & 0xAAAAAAAA) >> 1 | (n & 0x55555555) << 1, ensure parenthesis grouping around shifts and bitwise ANDs before bitwise OR.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Swap bits at even and odd index positions, pairwise bit transposition, constant instruction count.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: 0xAAAAAAAA (1010...) isolates all bits at odd positions; 0x55555555 (0101...) isolates all bits at even positions.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Sign-extension on odd-bit right shift: Shifting (n & 0xAAAAAAAA) right by 1 using signed >> can propagate the sign bit if the 31st bit is set. Use logical shift >>> or mask with 0x7FFFFFFF.

  • Hex mask typos: 0xAAAA is only 16 bits; a 32-bit integer requires 8 hex digits (0xAAAAAAAA and 0x55555555).

  • Iterating bit-by-bit: Looping 16 times with swaps is needlessly slow when two bitwise masks accomplish the swap in 3 CPU cycles.

The 60-Second Interview Pitch

Say this out loud before you type a single line

I isolate all odd bits using the mask 0xAAAAAAAA and shift them right by 1 into even positions. Concurrently, I isolate all even bits using 0x55555555 and shift them left by 1 into odd positions. Finally, I combine the two shifted values using bitwise OR. Runs in O(1) constant time with zero extra space.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(1)

Look at the execution steps: Masks even bits with 0xAAAAAAAA and shifts right by 1; masks odd bits with 0x55555555 and shifts left by 1; combines with bitwise OR: ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1). Runs in 3 CPU instructions.

SPACE COMPLEXITY

O(1) Auxiliary

Look at memory allocations: Call stack uses O(1). Single 32-bit integer in CPU register.

Formal Recurrence Relation

T=3 CPU instructions=O(1)T = 3 \text{ CPU instructions} = O(1)T=3 CPU instructions=O(1)

Derivation Progression

Even Bit Mask & Shift

(n \& 0xAAAAAAAA) >> 1

Extracts all even-positioned bits and shifts them to odd positions.

Odd Bit Mask & Shift

(n \& 0x55555555) << 1

Extracts all odd-positioned bits and shifts them to even positions.

Bitwise Recombination

even | odd

Combines swapped bits in single constant-time OR instruction.

Variable Definitions

323232

Fixed 32-bit word width (3 constant CPU register operations)

Memory Architecture & Bounds

🟣 Call Stack

O(1)

🔵 Auxiliary Heap

O(1) CPU register

🟢 Output Space

O(1) 32-bit integer

Boundary Best / Worst Cases

Best Case

O(1)O(1)O(1)

Average Case

O(1)O(1)O(1)

Worst Case

O(1)O(1)O(1)

Pointer Invariant Transition Progression

Pointer Invariant Transition Progression
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

The problem asks to "swap odd and even bits in an integer with as few operations as possible." Bit 0 and Bit 1 swap, Bit 2 and Bit 3 swap, etc. Iterating bit-by-bit is slow and unnecessary. The structural trigger is SIMD-style Whole-Word Masking: we isolate all even bits with an even-bit mask, isolate all odd bits with an odd-bit mask, shift each into their complementary positions, and recombine with bitwise OR.

CONSTRAINTS & BOUNDS

Input is a 32-bit integer. The even mask for bits 0, 2, 4... is 0x55555555 (...01010101). The odd mask for bits 1, 3, 5... is 0xAAAAAAAA (...10101010). Time complexity must be strictly O(1)O(1)O(1) using zero loops.

FAANG PRODUCTION TRAPS & EDGE CASES

In typed languages, shifting signed negative numbers right with >> propagates sign bits; an unsigned right shift >>> or casting to unsigned integer is necessary. In Python, large integers must be masked with 0xFFFFFFFF to simulate 32-bit unsigned boundaries.

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