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•Math & Geometry
MediumLC 7

Reverse Integer (LeetCode 7)

Target Frequency:AmazonMicrosoftGoogle

Take a signed 32-bit integer x and flip its digits end to end. If that flipped value would spill outside the signed 32-bit window [-231, 231 - 1], return 0 instead.

Treat 64-bit integer storage (signed or unsigned) as unavailable to you.

Worked Examples

Example 1
Input:x = 123
Output:321
Explanation: 123 reversed is 321.
Example 2
Input:x = -123
Output:-321
Explanation: The sign stays: -123 becomes -321.
Example 3
Input:x = 120
Output:21
Explanation: 120 reversed is 021, which is 21.

⚖️Formal Constraints & Bounds

  • -231 <= x <= 231 - 1

Deep-Dive & Conceptual Insights

Core Insight

Repeatedly pop the last digit via x % 10 and push it onto the reversed result. Before multiplying by 10, check that rev <= (231 - 1) // 10 to avoid 32-bit arithmetic overflow.

Real-World Scenario & Production Applications

Low-level serial communication packet decoding, endianness conversion, hardware register integer serialization.

Worked on Paper

The Math, Step by Step

1. The two operations that read digits

Every whole number x≥0x \ge 0x≥0 splits into its last digit and the rest:

x=10⋅q+dd=x mod 10q=⌊x/10⌋x = 10 \cdot q + d \qquad d = x \bmod 10 \qquad q = \lfloor x / 10 \rfloorx=10⋅q+dd=xmod10q=⌊x/10⌋

Here x mod 10x \bmod 10xmod10 is the remainder after dividing by 10, which is the last digit. ⌊x/10⌋\lfloor x / 10 \rfloor⌊x/10⌋ is the quotient rounded down, which is xxx with its last digit removed. In Python they are x % 10 and x // 10. For x=123x = 123x=123, the last digit is d=3d = 3d=3 and the rest is q=12q = 12q=12.

The reverse step is the opposite: appending a digit ddd to the right of a number rrr gives 10⋅r+d10 \cdot r + d10⋅r+d. So the code reads digits from the right end of x and appends them to the right end of res. This builds the digits in reverse order.

2. One round of the loop

Each round moves one digit from x to res:

LineMathEffect
digit = x % 10d=x mod 10d = x \bmod 10d=xmod10reads the last digit of x
x //= 10x←⌊x/10⌋x \leftarrow \lfloor x / 10 \rfloorx←⌊x/10⌋removes that digit from x
res = res * 10 + digitr←10⋅r+dr \leftarrow 10 \cdot r + dr←10⋅r+dappends it to res

The loop runs while x > 0, so it runs once per digit of x.

3. The 32-bit bound, checked before it is crossed

The result must fit in a signed 32-bit integer, which holds values from −231=−2147483648-2^{31} = -2147483648−231=−2147483648 to 231−1=21474836472^{31} - 1 = 2147483647231−1=2147483647. The problem also says to act as if no larger integer type exists. So the code may never compute a value above INT_MAX and check it afterwards. It must decide before the multiplication whether res * 10 + digit would be too large.

Write INT_MAX=2147483647=10⋅214748364+7\text{INT\_MAX} = 2147483647 = 10 \cdot 214748364 + 7INT_MAX=2147483647=10⋅214748364+7. Then 10⋅r+d>INT_MAX10 \cdot r + d > \text{INT\_MAX}10⋅r+d>INT_MAX in exactly two cases:

CaseTest in the codeWhy the new value is too large
r>214748364r > 214748364r>214748364res > INT_MAX // 10then 10⋅r≥214748365010 \cdot r \ge 214748365010⋅r≥2147483650, which is already too large
r=214748364r = 214748364r=214748364 and d>7d > 7d>7res == INT_MAX // 10 and digit > 7then 10⋅r+d≥214748364810 \cdot r + d \ge 214748364810⋅r+d≥2147483648

If r<214748364r < 214748364r<214748364, then 10⋅r+d≤2147483630+910 \cdot r + d \le 2147483630 + 910⋅r+d≤2147483630+9, which fits. If r=214748364r = 214748364r=214748364 and d≤7d \le 7d≤7, the new value is at most 214748364721474836472147483647, which also fits. So the test is exact. INT_MAX // 10 is 214748364214748364214748364, and the 7 is INT_MAX % 10.

4. Why the code takes the absolute value first

Python's % and // round toward minus infinity. So for a negative number, -123 % 10 is 7, not -3, and -123 // 10 is -13, not -12. The digit rule of part 1 would read wrong digits. The code avoids this: it saves sign, reverses abs(x), and multiplies by sign at the end.

The check in part 3 compares against INT_MAX only, even for negative inputs. This is safe for every 32-bit input. res can reach 214748364214748364214748364 only after 9 digits. The 10th and last digit is then the first digit of x. A 32-bit value has at most 10 digits, and a 10-digit one starts with 1 or 2. So that last digit is never greater than 7. The last line, return res if INT_MIN <= res <= INT_MAX else 0, is a second check of the same bound.

An example where the bound decides: x = 1463847412 reverses to 214748364121474836412147483641. Before the last round, res is 214748364214748364214748364 and the digit is 1. Since 1≤71 \le 71≤7, the value fits and the code returns 214748364121474836412147483641. For x = 1534236469, the reversal would be 964632435196463243519646324351. Before the last round res is 964632435964632435964632435, which is greater than 214748364214748364214748364. So the code returns 0 without ever computing the large value.

5. Example 1 by hand

x = 123, so sign = 1.

Rounddigit = x % 10x after x //= 10Checkres = res * 10 + digit
13120≤2147483640 \le 2147483640≤214748364, passes0⋅10+3=30 \cdot 10 + 3 = 30⋅10+3=3
2213≤2147483643 \le 2147483643≤214748364, passes3⋅10+2=323 \cdot 10 + 2 = 323⋅10+2=32
31032≤21474836432 \le 21474836432≤214748364, passes32⋅10+1=32132 \cdot 10 + 1 = 32132⋅10+1=321

x is now 0, so the loop stops. The code returns 321⋅1=321321 \cdot 1 = 321321⋅1=321, the expected output.

6. Example 2 by hand

x = -123. The code sets sign = -1 and x = 123. The three rounds are the same as in Example 1, so res ends as 321. The code returns 321⋅(−1)=−321321 \cdot (-1) = -321321⋅(−1)=−321, the expected output.

7. From the math to the code
MathIn reverse
231−12^{31} - 1231−1 and −231-2^{31}−231INT_MAX = 2**31 - 1 and INT_MIN = -2**31
work on ∣x∣\lvert x \rvert∣x∣, remember the signsign = -1 if x < 0 else 1 and x = abs(x)
d=x mod 10d = x \bmod 10d=xmod10, x←⌊x/10⌋x \leftarrow \lfloor x / 10 \rfloorx←⌊x/10⌋digit = x % 10 and x //= 10
10⋅r+d>INT_MAX10 \cdot r + d > \text{INT\_MAX}10⋅r+d>INT_MAX, tested before it is computedif res > INT_MAX // 10 or (res == INT_MAX // 10 and digit > 7): followed by return 0
r←10⋅r+dr \leftarrow 10 \cdot r + dr←10⋅r+dres = res * 10 + digit
put the sign backres *= sign

The loop runs once per digit, and a 32-bit value has at most 10 digits. So the code takes O(log⁡∣x∣)O(\log |x|)O(log∣x∣) time, which is at most 10 rounds, and O(1)O(1)O(1) space.

Code Shape
Archetype Code Shape
Python
1INT_MAX, INT_MIN = 2**31 - 1, -2**31
2sign = -1 if x < 0 else 1
3x = abs(x)
4res = 0
5while x > 0:
6 digit = x % 10
7 x //= 10
8 if res > INT_MAX // 10 or (res == INT_MAX // 10 and digit > 7):
9 return 0
10 res = res * 10 + digit
11res *= sign
12return res if INT_MIN <= res <= INT_MAX else 0

Conceptual Narrative

Reversing decimal digits of a 32-bit signed integer requires extracting modulo-10 digits and detecting arithmetic overflow before multiplication.

🧭 Conceptual Foundation & Pattern Intuition

Given a 32-bit signed integer xxx, reverse its digits without using 64-bit integers (long). Modulo arithmetic extracts digits: digit = x % 10; x //= 10. The challenge is detecting overflow BEFORE executing res = res * 10 + digit, as exceeding [−231,231−1][-2^{31}, 2^{31} - 1][−231,231−1] causes integer overflow.

🏟️ The Analogy: The Odometer Stop

Imagine an odometer with a hard physical limit at 2,147,483,647. Before advancing the dial by a factor of 10 and adding a final digit, you verify whether the odometer already reads >214,748,364> 214,748,364>214,748,364. If it does, any further addition will break the mechanism.

🔑 Why It Works

Checking against INT_MAX // 10 prevents overflow before it occurs.

  • Python negative modulo quirk: In Python, -123 % 10 yields 7 (not -3), and -123 // 10 yields -13. Strip the sign with abs(x) first before modulo arithmetic.

  • Post-facto overflow checking: Checking if res > 2**31 - 1 after computing res * 10 causes an integer trap/crash in 32-bit hardware. Check bounds before multiplication.

  • Handling the −231-2^{31}−231 edge case: In C/C++, abs(-2147483648) exceeds INT_MAX and invokes undefined behavior. Handle −231-2^{31}−231 explicitly as an overflow case.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Reverse 32-bit signed integer digits, overflow guard [-2^31, 2^31 - 1], return 0 on overflow.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: Accumulating rev = rev * 10 + digit must never exceed (231 - 1) or drop below -231 at any intermediate step.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • The card's trap: test res > INT_MAX // 10 (or res == INT_MAX // 10 and digit > 7) before res * 10 + digit.

  • Asymmetric boundaries: INT_MAX is 2147483647 (ends in 7) while INT_MIN is -2147483648 (ends in 8), so the blueprint also checks the final res against [INT_MIN, INT_MAX] after the sign is back.

  • The last digit popped is x's first digit, at most 2 for a 32-bit input, so digit > 7 never fires on this problem; keep it anyway, since it makes the same check correct for any digits, as in a parser.

The 60-Second Interview Pitch

Say this out loud before you type a single line

I'd use Digit Manipulation: take the number apart one digit at a time and rebuild it in reverse, without a string. I save the sign, work on abs(x), and loop while x > 0: digit = x % 10 reads the last digit, x //= 10 drops it, and res = res * 10 + digit appends it on the right. Reading from the right while appending on the right reverses the digits, and working on the absolute value avoids Python's rounding of % and // toward minus infinity for negatives. The trap is overflow. The answer must fit in a 32-bit signed integer, so before the multiply I return 0 if res > INT_MAX // 10, or if res == INT_MAX // 10 and digit > 7; checking after the multiply is too late in a fixed-width language, where the product has already wrapped. Each loop drops one digit, so it's O(log10 |x|) time and O(1) space.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(log10 |X|)

Look at the execution steps: Extracts digits via mod 10 and divides by 10 in while loop. Executes at most log10(2^31 - 1) <= 10 iterations. Checks 32-bit signed integer overflow before multiplying by 10. So O(log10 |x|) time, which is at most 10 steps for a 32-bit input, and O(1) space.

SPACE COMPLEXITY

O(1) Auxiliary

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

Formal Recurrence Relation

T(X) = ⌊ log_{10} |X| ⌋ + 1 ≤ 10 = O(1)

Derivation Progression

Digit Extraction

digit = x (mod 10), x = x // 10

Pops last digit from integer in O(1).

32-Bit Overflow Verification

if rev > (2^{31}-1)/10: return 0

Prevents integer overflow before multiplication in O(1).

Fixed Digit Bound

≤ 10 iterations

At most 10 decimal digits for 32-bit signed integer.

Variable Definitions

XXX

Magnitude of the input integer (at most 10 decimal digits for 32-bit int)

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(1) Single integer register

🟢 Output Space

O(1) Reversed 32-bit integer

Boundary Best / Worst Cases

Best Case

O(1)O(1)O(1) for single-digit numbers.

Average Case

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

Worst Case

O(1)O(1)O(1) (at most 10 iterations).

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 triggers are "reverse digits of a signed 32-bit integer" and "return 0 if reversing causes the value to go outside [-231, 231 - 1]". The junior trap is converting to a string or relying on 64-bit integers (long long in C++ / BigInt in Python), which violates the spirit of 32-bit hardware constraints. A Senior SWE immediately applies Integer Arithmetic Digit Extraction with predictive overflow detection before mutation.

CONSTRAINTS & BOUNDS

Input is 32-bit signed: −231≤x≤231−1-2^{31} \le x \le 2^{31} - 1−231≤x≤231−1. Time budget is O(log⁡10∣x∣)≤10O(\log_{10} |x|) \le 10O(log10​∣x∣)≤10 operations. Auxiliary space is strictly O(1)O(1)O(1). Boundary limits: INT_MAX=2147483647\text{INT\_MAX} = 2147483647INT_MAX=2147483647, INT_MIN=−2147483648\text{INT\_MIN} = -2147483648INT_MIN=−2147483648.

FAANG PRODUCTION TRAPS & EDGE CASES

In C and Java, abs(x) itself overflows for x=−231x = -2^{31}x=−231: it has no positive 32-bit twin. There, either take the absolute value in 64 bits or keep x negative and work with negative digits (C and Java's % keeps the dividend's sign).

Theory Context•Math & Geometry
MediumLC 7

Reverse Integer (LeetCode 7)

Target Frequency:AmazonMicrosoftGoogle

Take a signed 32-bit integer x and flip its digits end to end. If that flipped value would spill outside the signed 32-bit window [-231, 231 - 1], return 0 instead.

Treat 64-bit integer storage (signed or unsigned) as unavailable to you.

Worked Examples

Example 1
Input:x = 123
Output:321
Explanation: 123 reversed is 321.
Example 2
Input:x = -123
Output:-321
Explanation: The sign stays: -123 becomes -321.
Example 3
Input:x = 120
Output:21
Explanation: 120 reversed is 021, which is 21.

⚖️Formal Constraints & Bounds

  • -231 <= x <= 231 - 1

Deep-Dive & Conceptual Insights

Core Insight

Repeatedly pop the last digit via x % 10 and push it onto the reversed result. Before multiplying by 10, check that rev <= (231 - 1) // 10 to avoid 32-bit arithmetic overflow.

Real-World Scenario & Production Applications

Low-level serial communication packet decoding, endianness conversion, hardware register integer serialization.

Worked on Paper

The Math, Step by Step

1. The two operations that read digits

Every whole number x≥0x \ge 0x≥0 splits into its last digit and the rest:

x=10⋅q+dd=x mod 10q=⌊x/10⌋x = 10 \cdot q + d \qquad d = x \bmod 10 \qquad q = \lfloor x / 10 \rfloorx=10⋅q+dd=xmod10q=⌊x/10⌋

Here x mod 10x \bmod 10xmod10 is the remainder after dividing by 10, which is the last digit. ⌊x/10⌋\lfloor x / 10 \rfloor⌊x/10⌋ is the quotient rounded down, which is xxx with its last digit removed. In Python they are x % 10 and x // 10. For x=123x = 123x=123, the last digit is d=3d = 3d=3 and the rest is q=12q = 12q=12.

The reverse step is the opposite: appending a digit ddd to the right of a number rrr gives 10⋅r+d10 \cdot r + d10⋅r+d. So the code reads digits from the right end of x and appends them to the right end of res. This builds the digits in reverse order.

2. One round of the loop

Each round moves one digit from x to res:

LineMathEffect
digit = x % 10d=x mod 10d = x \bmod 10d=xmod10reads the last digit of x
x //= 10x←⌊x/10⌋x \leftarrow \lfloor x / 10 \rfloorx←⌊x/10⌋removes that digit from x
res = res * 10 + digitr←10⋅r+dr \leftarrow 10 \cdot r + dr←10⋅r+dappends it to res

The loop runs while x > 0, so it runs once per digit of x.

3. The 32-bit bound, checked before it is crossed

The result must fit in a signed 32-bit integer, which holds values from −231=−2147483648-2^{31} = -2147483648−231=−2147483648 to 231−1=21474836472^{31} - 1 = 2147483647231−1=2147483647. The problem also says to act as if no larger integer type exists. So the code may never compute a value above INT_MAX and check it afterwards. It must decide before the multiplication whether res * 10 + digit would be too large.

Write INT_MAX=2147483647=10⋅214748364+7\text{INT\_MAX} = 2147483647 = 10 \cdot 214748364 + 7INT_MAX=2147483647=10⋅214748364+7. Then 10⋅r+d>INT_MAX10 \cdot r + d > \text{INT\_MAX}10⋅r+d>INT_MAX in exactly two cases:

CaseTest in the codeWhy the new value is too large
r>214748364r > 214748364r>214748364res > INT_MAX // 10then 10⋅r≥214748365010 \cdot r \ge 214748365010⋅r≥2147483650, which is already too large
r=214748364r = 214748364r=214748364 and d>7d > 7d>7res == INT_MAX // 10 and digit > 7then 10⋅r+d≥214748364810 \cdot r + d \ge 214748364810⋅r+d≥2147483648

If r<214748364r < 214748364r<214748364, then 10⋅r+d≤2147483630+910 \cdot r + d \le 2147483630 + 910⋅r+d≤2147483630+9, which fits. If r=214748364r = 214748364r=214748364 and d≤7d \le 7d≤7, the new value is at most 214748364721474836472147483647, which also fits. So the test is exact. INT_MAX // 10 is 214748364214748364214748364, and the 7 is INT_MAX % 10.

4. Why the code takes the absolute value first

Python's % and // round toward minus infinity. So for a negative number, -123 % 10 is 7, not -3, and -123 // 10 is -13, not -12. The digit rule of part 1 would read wrong digits. The code avoids this: it saves sign, reverses abs(x), and multiplies by sign at the end.

The check in part 3 compares against INT_MAX only, even for negative inputs. This is safe for every 32-bit input. res can reach 214748364214748364214748364 only after 9 digits. The 10th and last digit is then the first digit of x. A 32-bit value has at most 10 digits, and a 10-digit one starts with 1 or 2. So that last digit is never greater than 7. The last line, return res if INT_MIN <= res <= INT_MAX else 0, is a second check of the same bound.

An example where the bound decides: x = 1463847412 reverses to 214748364121474836412147483641. Before the last round, res is 214748364214748364214748364 and the digit is 1. Since 1≤71 \le 71≤7, the value fits and the code returns 214748364121474836412147483641. For x = 1534236469, the reversal would be 964632435196463243519646324351. Before the last round res is 964632435964632435964632435, which is greater than 214748364214748364214748364. So the code returns 0 without ever computing the large value.

5. Example 1 by hand

x = 123, so sign = 1.

Rounddigit = x % 10x after x //= 10Checkres = res * 10 + digit
13120≤2147483640 \le 2147483640≤214748364, passes0⋅10+3=30 \cdot 10 + 3 = 30⋅10+3=3
2213≤2147483643 \le 2147483643≤214748364, passes3⋅10+2=323 \cdot 10 + 2 = 323⋅10+2=32
31032≤21474836432 \le 21474836432≤214748364, passes32⋅10+1=32132 \cdot 10 + 1 = 32132⋅10+1=321

x is now 0, so the loop stops. The code returns 321⋅1=321321 \cdot 1 = 321321⋅1=321, the expected output.

6. Example 2 by hand

x = -123. The code sets sign = -1 and x = 123. The three rounds are the same as in Example 1, so res ends as 321. The code returns 321⋅(−1)=−321321 \cdot (-1) = -321321⋅(−1)=−321, the expected output.

7. From the math to the code
MathIn reverse
231−12^{31} - 1231−1 and −231-2^{31}−231INT_MAX = 2**31 - 1 and INT_MIN = -2**31
work on ∣x∣\lvert x \rvert∣x∣, remember the signsign = -1 if x < 0 else 1 and x = abs(x)
d=x mod 10d = x \bmod 10d=xmod10, x←⌊x/10⌋x \leftarrow \lfloor x / 10 \rfloorx←⌊x/10⌋digit = x % 10 and x //= 10
10⋅r+d>INT_MAX10 \cdot r + d > \text{INT\_MAX}10⋅r+d>INT_MAX, tested before it is computedif res > INT_MAX // 10 or (res == INT_MAX // 10 and digit > 7): followed by return 0
r←10⋅r+dr \leftarrow 10 \cdot r + dr←10⋅r+dres = res * 10 + digit
put the sign backres *= sign

The loop runs once per digit, and a 32-bit value has at most 10 digits. So the code takes O(log⁡∣x∣)O(\log |x|)O(log∣x∣) time, which is at most 10 rounds, and O(1)O(1)O(1) space.

Code Shape
Archetype Code Shape
Python
1INT_MAX, INT_MIN = 2**31 - 1, -2**31
2sign = -1 if x < 0 else 1
3x = abs(x)
4res = 0
5while x > 0:
6 digit = x % 10
7 x //= 10
8 if res > INT_MAX // 10 or (res == INT_MAX // 10 and digit > 7):
9 return 0
10 res = res * 10 + digit
11res *= sign
12return res if INT_MIN <= res <= INT_MAX else 0

Conceptual Narrative

Reversing decimal digits of a 32-bit signed integer requires extracting modulo-10 digits and detecting arithmetic overflow before multiplication.

🧭 Conceptual Foundation & Pattern Intuition

Given a 32-bit signed integer xxx, reverse its digits without using 64-bit integers (long). Modulo arithmetic extracts digits: digit = x % 10; x //= 10. The challenge is detecting overflow BEFORE executing res = res * 10 + digit, as exceeding [−231,231−1][-2^{31}, 2^{31} - 1][−231,231−1] causes integer overflow.

🏟️ The Analogy: The Odometer Stop

Imagine an odometer with a hard physical limit at 2,147,483,647. Before advancing the dial by a factor of 10 and adding a final digit, you verify whether the odometer already reads >214,748,364> 214,748,364>214,748,364. If it does, any further addition will break the mechanism.

🔑 Why It Works

Checking against INT_MAX // 10 prevents overflow before it occurs.

  • Python negative modulo quirk: In Python, -123 % 10 yields 7 (not -3), and -123 // 10 yields -13. Strip the sign with abs(x) first before modulo arithmetic.

  • Post-facto overflow checking: Checking if res > 2**31 - 1 after computing res * 10 causes an integer trap/crash in 32-bit hardware. Check bounds before multiplication.

  • Handling the −231-2^{31}−231 edge case: In C/C++, abs(-2147483648) exceeds INT_MAX and invokes undefined behavior. Handle −231-2^{31}−231 explicitly as an overflow case.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Reverse 32-bit signed integer digits, overflow guard [-2^31, 2^31 - 1], return 0 on overflow.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: Accumulating rev = rev * 10 + digit must never exceed (231 - 1) or drop below -231 at any intermediate step.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • The card's trap: test res > INT_MAX // 10 (or res == INT_MAX // 10 and digit > 7) before res * 10 + digit.

  • Asymmetric boundaries: INT_MAX is 2147483647 (ends in 7) while INT_MIN is -2147483648 (ends in 8), so the blueprint also checks the final res against [INT_MIN, INT_MAX] after the sign is back.

  • The last digit popped is x's first digit, at most 2 for a 32-bit input, so digit > 7 never fires on this problem; keep it anyway, since it makes the same check correct for any digits, as in a parser.

The 60-Second Interview Pitch

Say this out loud before you type a single line

I'd use Digit Manipulation: take the number apart one digit at a time and rebuild it in reverse, without a string. I save the sign, work on abs(x), and loop while x > 0: digit = x % 10 reads the last digit, x //= 10 drops it, and res = res * 10 + digit appends it on the right. Reading from the right while appending on the right reverses the digits, and working on the absolute value avoids Python's rounding of % and // toward minus infinity for negatives. The trap is overflow. The answer must fit in a 32-bit signed integer, so before the multiply I return 0 if res > INT_MAX // 10, or if res == INT_MAX // 10 and digit > 7; checking after the multiply is too late in a fixed-width language, where the product has already wrapped. Each loop drops one digit, so it's O(log10 |x|) time and O(1) space.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(log10 |X|)

Look at the execution steps: Extracts digits via mod 10 and divides by 10 in while loop. Executes at most log10(2^31 - 1) <= 10 iterations. Checks 32-bit signed integer overflow before multiplying by 10. So O(log10 |x|) time, which is at most 10 steps for a 32-bit input, and O(1) space.

SPACE COMPLEXITY

O(1) Auxiliary

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

Formal Recurrence Relation

T(X) = ⌊ log_{10} |X| ⌋ + 1 ≤ 10 = O(1)

Derivation Progression

Digit Extraction

digit = x (mod 10), x = x // 10

Pops last digit from integer in O(1).

32-Bit Overflow Verification

if rev > (2^{31}-1)/10: return 0

Prevents integer overflow before multiplication in O(1).

Fixed Digit Bound

≤ 10 iterations

At most 10 decimal digits for 32-bit signed integer.

Variable Definitions

XXX

Magnitude of the input integer (at most 10 decimal digits for 32-bit int)

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(1) Single integer register

🟢 Output Space

O(1) Reversed 32-bit integer

Boundary Best / Worst Cases

Best Case

O(1)O(1)O(1) for single-digit numbers.

Average Case

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

Worst Case

O(1)O(1)O(1) (at most 10 iterations).

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 triggers are "reverse digits of a signed 32-bit integer" and "return 0 if reversing causes the value to go outside [-231, 231 - 1]". The junior trap is converting to a string or relying on 64-bit integers (long long in C++ / BigInt in Python), which violates the spirit of 32-bit hardware constraints. A Senior SWE immediately applies Integer Arithmetic Digit Extraction with predictive overflow detection before mutation.

CONSTRAINTS & BOUNDS

Input is 32-bit signed: −231≤x≤231−1-2^{31} \le x \le 2^{31} - 1−231≤x≤231−1. Time budget is O(log⁡10∣x∣)≤10O(\log_{10} |x|) \le 10O(log10​∣x∣)≤10 operations. Auxiliary space is strictly O(1)O(1)O(1). Boundary limits: INT_MAX=2147483647\text{INT\_MAX} = 2147483647INT_MAX=2147483647, INT_MIN=−2147483648\text{INT\_MIN} = -2147483648INT_MIN=−2147483648.

FAANG PRODUCTION TRAPS & EDGE CASES

In C and Java, abs(x) itself overflows for x=−231x = -2^{31}x=−231: it has no positive 32-bit twin. There, either take the absolute value in 64 bits or keep x negative and work with negative digits (C and Java's % keeps the dividend's sign).

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