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

Find Greatest Common Divisor of Array (LeetCode 1979)

Target Frequency:AmazonGoogleMicrosoft

You get an array of positive integers, nums. Take its smallest value and its largest value, and return their greatest common divisor: the largest positive integer that divides both of them with no remainder.

Only those two values matter; the other values of nums play no part in the answer. When the smallest and the largest value are equal, as in [3,3], the answer is that value itself.

Worked Examples

Example 1
Input:nums = [2,5,6,9,10]
Output:2
20516293104min 2max 10
Explanation: The smallest value is 2 and the largest is 10. 2 divides 10, so their greatest common divisor is 2. (The five values together only share 1: just the two ends count.)
Example 2
Input:nums = [7,5,6,8,3]
Output:1
7051628334min 3max 8
Explanation: The ends are 3 and 8. No integer larger than 1 divides both, so the answer is 1.
Example 3
Input:nums = [3,3]
Output:3
3031min 3max 3
Explanation: Both ends are 3, and the largest integer dividing 3 is 3 itself.

⚖️Formal Constraints & Bounds

  • 2 <= nums.length <= 1000

  • 1 <= nums[i] <= 1000

Deep-Dive & Conceptual Insights

Core Insight

a % b is a minus a multiple of b, so the pairs (a, b) and (b, a % b) have exactly the same common divisors. Repeating the step shrinks the pair fast until b is 0, and then a is the greatest common divisor.

Real-World Scenario & Production Applications

Reducing a ratio to lowest terms: an image editor showing a 1920 x 1080 screen as 16:9, or a recipe tool scaling 12 eggs to 18 cups of flour down to 2:3, divides both numbers by their greatest common divisor.

Step-by-Step Execution Trace Table

Example 2, nums = [7,5,6,8,3]:

StepLineabWhy
1lo, hi = min(nums), max(nums)lo = 3, hi = 8: only the two ends count
2gcd(hi, lo)83The call starts with the larger value first
3a, b = b, a % b328 % 3 = 2, computed from the old a
4a, b = b, a % b213 % 2 = 1
5a, b = b, a % b102 % 1 = 0
6return a10b is 0, so a = 1 is the answer

With a = b first and b = a % b second, step 3 would compute 3 % 3 = 0 and return 3.

Worked on Paper

The Math, Step by Step

1. The number the code returns

The greatest common divisor of two positive whole numbers aaa and bbb, written gcd⁡(a,b)\gcd(a, b)gcd(a,b), is the largest whole number that divides both with no remainder. The problem asks for gcd⁡(hi,lo)\gcd(\text{hi}, \text{lo})gcd(hi,lo), where lo is the smallest value of nums and hi is the largest. findGCD finds the two ends with min and max, and gcd computes their greatest common divisor.

2. One step of Euclid's algorithm

Divide aaa by bbb: a=q⋅b+ra = q \cdot b + ra=q⋅b+r, where q=⌊a/b⌋q = \lfloor a / b \rfloorq=⌊a/b⌋ is the quotient and r=a mod br = a \bmod br=amodb is the remainder, with 0≤r<b0 \le r < b0≤r<b. Euclid's algorithm replaces the pair (a,b)(a, b)(a,b) with (b,r)(b, r)(b,r) and repeats:

gcd⁡(a,b)=gcd⁡(b, a mod b)gcd⁡(a,0)=a\gcd(a, b) = \gcd(b,\ a \bmod b) \qquad \gcd(a, 0) = agcd(a,b)=gcd(b, amodb)gcd(a,0)=a

CaseRuleWhat the loop does
b>0b > 0b>0gcd⁡(a,b)=gcd⁡(b,a mod b)\gcd(a, b) = \gcd(b, a \bmod b)gcd(a,b)=gcd(b,amodb)a, b = b, a % b
b=0b = 0b=0gcd⁡(a,0)=a\gcd(a, 0) = agcd(a,0)=a, because every number divides 0the loop stops and return a
3. Why one step keeps the answer, and why the loop ends

The common divisors stay the same. Take any ddd that divides both aaa and bbb. Then ddd divides r=a−q⋅br = a - q \cdot br=a−q⋅b, because it divides both terms. So ddd divides bbb and rrr. In the other direction, take any ddd that divides bbb and rrr. Then ddd divides a=q⋅b+ra = q \cdot b + ra=q⋅b+r. So the pairs (a,b)(a, b)(a,b) and (b,r)(b, r)(b,r) have exactly the same common divisors. The largest of them, the gcd, is the same too.

The loop ends. The new second number is r<br < br<b. So the second number shrinks in every step and stays at 0 or above. It reaches 0 after a finite number of steps. At that point the pair is (a,0)(a, 0)(a,0), and gcd⁡(a,0)=a\gcd(a, 0) = agcd(a,0)=a.

It ends fast. Every two steps at least halve the first number. So the loop runs O(log⁡M)O(\log M)O(logM) times, where MMM is the larger value. For values up to 1000, the most steps any pair needs is 14, for the pair (987,610)(987, 610)(987,610). These two numbers are neighbours in the Fibonacci sequence, the worst case for Euclid's algorithm.

4. Both values change at once, and the order of the arguments

a, b = b, a % b computes the right side first, with the old a and b, and then assigns both. Two separate lines, a = b then b = a % b, would compute b % b, which is always 0. The loop would then stop after one step and return the old b.

The code calls gcd(hi, lo), with the larger value first. With the smaller value first, the answer is still right. The first step only swaps the two, because lo % hi is lo when lo < hi. For example, gcd(3, 8) first becomes gcd(8, 3), one extra step.

When the smallest and largest values are equal, as in [3,3], the first step gives 3 mod 3=03 \bmod 3 = 03mod3=0. The code returns 3, the value itself.

5. Example 1 by hand

nums = [2,5,6,9,10], so lo = 2 and hi = 10. The call is gcd(10, 2).

Stepaba % bNew pair
11020(2,0)(2, 0)(2,0)

Now b is 0, so the loop stops and returns a = 2, the expected output. The values 5, 6 and 9 play no part.

6. Example 2 by hand

nums = [7,5,6,8,3], so lo = 3 and hi = 8. The call is gcd(8, 3).

Stepaba % bNew pair
1832(3,2)(3, 2)(3,2)
2321(2,1)(2, 1)(2,1)
3210(1,0)(1, 0)(1,0)

The loop returns a = 1, the expected output. By part 3, every pair in the table has the same common divisors as (8,3)(8, 3)(8,3), and the last pair (1,0)(1, 0)(1,0) shows that the only one is 1.

7. From the math to the code
MathIn the code
the two ends of numslo, hi = min(nums), max(nums)
gcd⁡(hi,lo)\gcd(\text{hi}, \text{lo})gcd(hi,lo)return gcd(hi, lo)
repeat while b>0b > 0b>0while b:
(a,b)→(b,a mod b)(a, b) \to (b, a \bmod b)(a,b)→(b,amodb)a, b = b, a % b
gcd⁡(a,0)=a\gcd(a, 0) = agcd(a,0)=areturn a

Finding min and max reads all NNN values, and Euclid's loop takes O(log⁡M)O(\log M)O(logM) steps. So the code takes O(N+log⁡M)O(N + \log M)O(N+logM) time and O(1)O(1)O(1) space, as its docstring says.

Code Shape
Archetype Code Shape
Python
1The pairs `(a, b)` and `(b, a % b)` have the same common divisors, and `gcd(a, 0)` is `a`: shrink the pair until `b` is 0.
2Keep this true: `gcd(a, b)` is the same at every step, and `b` gets smaller every step.
3Reduce `nums` to two numbers; then loop while the second number of the pair is not 0, replacing the pair each time; the answer is one of the two when the loop ends.
4The trap: update `a` and `b` in one statement. `a = b` first makes `b = a % b` compute `b % b`, always 0, and the loop returns the smaller value.

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

The obvious way to find the greatest common divisor is trial division: try lo, then lo - 1, and so on, until a number divides both values. That can take as many steps as the smaller value. Euclid's GCD never tries a candidate. It replaces the pair (a, b) with (b, a % b), a smaller pair with exactly the same common divisors, and stops when b is 0: then a is the answer. find_gcd only needs the two ends of nums, so it finds lo and hi and returns gcd(hi, lo).

🧱 The Analogy: Tiling a Floor With the Biggest Square

You want to cover a 8 x 3 floor with equal square tiles, as large as possible. Lay down 3 x 3 squares along the long side: two fit, and a 2 x 3 strip is left over. Whatever square tiles the whole floor must also tile that leftover strip, and the other way round, so the problem is now the 3 x 2 strip. One 2 x 2 square leaves a 1 x 2 strip, and 1 x 1 squares fill it exactly. The biggest square is 1 x 1, found in three cuts instead of trying every size. Each cut is one a % b.

🔑 Why It Works

a % b equals a - q * b for some whole number q. A number that divides a and b divides a - q * b; a number that divides b and a - q * b divides a. So gcd(a, b) == gcd(b, a % b) at every step, and when b reaches 0, gcd(a, 0) is simply a. The remainder is also small: whenever a >= b, a % b is less than half of a, so every two steps at least halve the pair. The one line that must be exact is the update: both new values come from the old pair, so a, b = b, a % b is a single statement.

  • Updating one value at a time: write a, b = b, a % b in one statement. a = b followed by b = a % b computes b % b == 0, so gcd(8, 3) returns 3 instead of 1.

  • Returning the wrong value: loop while b: and return a. The pair ends as (g, 0), so return b always gives 0.

  • Subtracting instead of taking the remainder: a - b again and again takes a / b steps (about 10^9 for gcd(109, 1)); % needs at most about 2 log2 of the smaller value.

  • The gcd of the wrong values: here it is min(nums) and max(nums) only. In [2,5,6,9,10] the answer is 2, while the gcd of all five values is 1.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

"Take its smallest value and its largest value", "return their greatest common divisor" and "the largest positive integer that divides both of them with no remainder": a common divisor of two whole numbers. That is the signal for Euclid's GCD: replace the pair by (b, a % b) until b is 0, instead of trying every divisor.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

The stopping decision: loop while b is not 0; the moment b == 0, return a, because gcd(a, 0) is a.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • The card's trap: a, b = b, a % b in one statement (gotcha 1: gcd(8, 3) for [7,5,6,8,3] would return 3).

  • The argument order does not matter: gcd(lo, hi) works too, because its first step computes lo % hi == lo and swaps the pair.

  • lo and hi can come from one loop instead of two calls to min and max; both are O(N), so pick whichever reads more clearly.

The 60-Second Interview Pitch

Say this out loud before you type a single line

I'd use Euclid's GCD. The problem only cares about the smallest and the largest value, so I find them in one pass each and run Euclid's algorithm on that pair. The idea is that a and b have exactly the same common divisors as b and a mod b, because a mod b is a minus a multiple of b. So I keep replacing the pair with b and a mod b until b is zero, and then a is the answer. The numbers at least halve every two steps, so the loop is logarithmic. The trap is the update: I write a comma b equals b comma a mod b as one statement, because setting a to b first would compute b mod b, which is always zero, and I'd return the smaller number. That's O(N plus log M) time and O(1) extra space.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N + log M)

min(nums) and max(nums) each read the N values once: O(N). Then gcd(hi, lo) runs while b:. Each step does one % and one swap. Whenever a >= b, a % b is less than half of a (if b <= a / 2 the remainder is below b; otherwise it is a - b, below a / 2), and two steps turn the pair's first value a into a % b. So the first value at least halves every two steps, and the loop runs at most about 2 * log2(M) times: O(log M). Total: O(N + log M).

SPACE COMPLEXITY

O(1)

find_gcd keeps lo and hi; gcd keeps a and b and loops instead of recursing, so no call stack grows: O(1). The answer is one integer.

Formal Recurrence Relation

T(N, M) = 2N (min and max) + 2 · log2(M) (remainder steps) = O(N + log M)

Derivation Progression

Find the two ends

O(N)

min(nums) and max(nums) each read every value once.

One remainder step

O(1)

a, b = b, a % b is one % and one swap.

Number of steps

O(log M)

Whenever a >= b, a % b < a / 2, and two steps turn a into a % b, so a at least halves every two steps.

Total

O(N + log M)

One pass for the ends, then a logarithmic number of constant-time steps.

Variable Definitions

NNN

Number of values, len(nums) (at most 1000)

MMM

The largest value, max(nums) (at most 1000)

Memory Architecture & Bounds

🟣 Call Stack

O(1): gcd loops instead of recursing

🔵 Auxiliary Heap

O(1): lo, hi, a, b

🟢 Output Space

O(1): one integer

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N): lo divides hi, so one remainder step ends the loop

Average Case

O(N+log⁡M)O(N + \log M)O(N+logM)

Worst Case

O(N+log⁡M)O(N + \log M)O(N+logM): consecutive Fibonacci numbers such as 610 and 987 take the most steps (14)

Pointer Invariant Transition Progression

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

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: "greatest common divisor", "the largest positive integer that divides both of them", "take its smallest value and its largest value". Two whole numbers and their largest shared divisor: Euclid's GCD, a, b = b, a % b until b is 0.

CONSTRAINTS & BOUNDS

At most 100010001000 values, each at most 100010001000: min and max are 200020002000 reads, and Euclid on two values up to 100010001000 takes at most 141414 remainder steps (consecutive Fibonacci numbers, 610610610 and 987987987). Trial division would need up to 100010001000 checks here, and 10910^9109 for values up to 10910^9109.

FAANG PRODUCTION TRAPS & EDGE CASES

With huge integers, as in cryptography, each % is itself a long division, so libraries use binary GCD or Lehmer's variant to cut its cost. With negative inputs, languages disagree on the sign of % (in Python it follows the divisor, in C and Java the dividend), so take absolute values first. A recursive gcd costs one stack frame per step; the loop never overflows.

Core Algorithmic State Invariants

  1. Zero Is the Neutral Start

gcd(x, 0) == x, so a running gcd over many values can start at 0 and fold each value in with g = gcd(g, x). Here only two values matter, but the same fold handles every value when a problem asks for the gcd of all of them.

Theory Context•Math & Geometry
EasyLC 1979

Find Greatest Common Divisor of Array (LeetCode 1979)

Target Frequency:AmazonGoogleMicrosoft

You get an array of positive integers, nums. Take its smallest value and its largest value, and return their greatest common divisor: the largest positive integer that divides both of them with no remainder.

Only those two values matter; the other values of nums play no part in the answer. When the smallest and the largest value are equal, as in [3,3], the answer is that value itself.

Worked Examples

Example 1
Input:nums = [2,5,6,9,10]
Output:2
20516293104min 2max 10
Explanation: The smallest value is 2 and the largest is 10. 2 divides 10, so their greatest common divisor is 2. (The five values together only share 1: just the two ends count.)
Example 2
Input:nums = [7,5,6,8,3]
Output:1
7051628334min 3max 8
Explanation: The ends are 3 and 8. No integer larger than 1 divides both, so the answer is 1.
Example 3
Input:nums = [3,3]
Output:3
3031min 3max 3
Explanation: Both ends are 3, and the largest integer dividing 3 is 3 itself.

⚖️Formal Constraints & Bounds

  • 2 <= nums.length <= 1000

  • 1 <= nums[i] <= 1000

Deep-Dive & Conceptual Insights

Core Insight

a % b is a minus a multiple of b, so the pairs (a, b) and (b, a % b) have exactly the same common divisors. Repeating the step shrinks the pair fast until b is 0, and then a is the greatest common divisor.

Real-World Scenario & Production Applications

Reducing a ratio to lowest terms: an image editor showing a 1920 x 1080 screen as 16:9, or a recipe tool scaling 12 eggs to 18 cups of flour down to 2:3, divides both numbers by their greatest common divisor.

Step-by-Step Execution Trace Table

Example 2, nums = [7,5,6,8,3]:

StepLineabWhy
1lo, hi = min(nums), max(nums)lo = 3, hi = 8: only the two ends count
2gcd(hi, lo)83The call starts with the larger value first
3a, b = b, a % b328 % 3 = 2, computed from the old a
4a, b = b, a % b213 % 2 = 1
5a, b = b, a % b102 % 1 = 0
6return a10b is 0, so a = 1 is the answer

With a = b first and b = a % b second, step 3 would compute 3 % 3 = 0 and return 3.

Worked on Paper

The Math, Step by Step

1. The number the code returns

The greatest common divisor of two positive whole numbers aaa and bbb, written gcd⁡(a,b)\gcd(a, b)gcd(a,b), is the largest whole number that divides both with no remainder. The problem asks for gcd⁡(hi,lo)\gcd(\text{hi}, \text{lo})gcd(hi,lo), where lo is the smallest value of nums and hi is the largest. findGCD finds the two ends with min and max, and gcd computes their greatest common divisor.

2. One step of Euclid's algorithm

Divide aaa by bbb: a=q⋅b+ra = q \cdot b + ra=q⋅b+r, where q=⌊a/b⌋q = \lfloor a / b \rfloorq=⌊a/b⌋ is the quotient and r=a mod br = a \bmod br=amodb is the remainder, with 0≤r<b0 \le r < b0≤r<b. Euclid's algorithm replaces the pair (a,b)(a, b)(a,b) with (b,r)(b, r)(b,r) and repeats:

gcd⁡(a,b)=gcd⁡(b, a mod b)gcd⁡(a,0)=a\gcd(a, b) = \gcd(b,\ a \bmod b) \qquad \gcd(a, 0) = agcd(a,b)=gcd(b, amodb)gcd(a,0)=a

CaseRuleWhat the loop does
b>0b > 0b>0gcd⁡(a,b)=gcd⁡(b,a mod b)\gcd(a, b) = \gcd(b, a \bmod b)gcd(a,b)=gcd(b,amodb)a, b = b, a % b
b=0b = 0b=0gcd⁡(a,0)=a\gcd(a, 0) = agcd(a,0)=a, because every number divides 0the loop stops and return a
3. Why one step keeps the answer, and why the loop ends

The common divisors stay the same. Take any ddd that divides both aaa and bbb. Then ddd divides r=a−q⋅br = a - q \cdot br=a−q⋅b, because it divides both terms. So ddd divides bbb and rrr. In the other direction, take any ddd that divides bbb and rrr. Then ddd divides a=q⋅b+ra = q \cdot b + ra=q⋅b+r. So the pairs (a,b)(a, b)(a,b) and (b,r)(b, r)(b,r) have exactly the same common divisors. The largest of them, the gcd, is the same too.

The loop ends. The new second number is r<br < br<b. So the second number shrinks in every step and stays at 0 or above. It reaches 0 after a finite number of steps. At that point the pair is (a,0)(a, 0)(a,0), and gcd⁡(a,0)=a\gcd(a, 0) = agcd(a,0)=a.

It ends fast. Every two steps at least halve the first number. So the loop runs O(log⁡M)O(\log M)O(logM) times, where MMM is the larger value. For values up to 1000, the most steps any pair needs is 14, for the pair (987,610)(987, 610)(987,610). These two numbers are neighbours in the Fibonacci sequence, the worst case for Euclid's algorithm.

4. Both values change at once, and the order of the arguments

a, b = b, a % b computes the right side first, with the old a and b, and then assigns both. Two separate lines, a = b then b = a % b, would compute b % b, which is always 0. The loop would then stop after one step and return the old b.

The code calls gcd(hi, lo), with the larger value first. With the smaller value first, the answer is still right. The first step only swaps the two, because lo % hi is lo when lo < hi. For example, gcd(3, 8) first becomes gcd(8, 3), one extra step.

When the smallest and largest values are equal, as in [3,3], the first step gives 3 mod 3=03 \bmod 3 = 03mod3=0. The code returns 3, the value itself.

5. Example 1 by hand

nums = [2,5,6,9,10], so lo = 2 and hi = 10. The call is gcd(10, 2).

Stepaba % bNew pair
11020(2,0)(2, 0)(2,0)

Now b is 0, so the loop stops and returns a = 2, the expected output. The values 5, 6 and 9 play no part.

6. Example 2 by hand

nums = [7,5,6,8,3], so lo = 3 and hi = 8. The call is gcd(8, 3).

Stepaba % bNew pair
1832(3,2)(3, 2)(3,2)
2321(2,1)(2, 1)(2,1)
3210(1,0)(1, 0)(1,0)

The loop returns a = 1, the expected output. By part 3, every pair in the table has the same common divisors as (8,3)(8, 3)(8,3), and the last pair (1,0)(1, 0)(1,0) shows that the only one is 1.

7. From the math to the code
MathIn the code
the two ends of numslo, hi = min(nums), max(nums)
gcd⁡(hi,lo)\gcd(\text{hi}, \text{lo})gcd(hi,lo)return gcd(hi, lo)
repeat while b>0b > 0b>0while b:
(a,b)→(b,a mod b)(a, b) \to (b, a \bmod b)(a,b)→(b,amodb)a, b = b, a % b
gcd⁡(a,0)=a\gcd(a, 0) = agcd(a,0)=areturn a

Finding min and max reads all NNN values, and Euclid's loop takes O(log⁡M)O(\log M)O(logM) steps. So the code takes O(N+log⁡M)O(N + \log M)O(N+logM) time and O(1)O(1)O(1) space, as its docstring says.

Code Shape
Archetype Code Shape
Python
1The pairs `(a, b)` and `(b, a % b)` have the same common divisors, and `gcd(a, 0)` is `a`: shrink the pair until `b` is 0.
2Keep this true: `gcd(a, b)` is the same at every step, and `b` gets smaller every step.
3Reduce `nums` to two numbers; then loop while the second number of the pair is not 0, replacing the pair each time; the answer is one of the two when the loop ends.
4The trap: update `a` and `b` in one statement. `a = b` first makes `b = a % b` compute `b % b`, always 0, and the loop returns the smaller value.

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

The obvious way to find the greatest common divisor is trial division: try lo, then lo - 1, and so on, until a number divides both values. That can take as many steps as the smaller value. Euclid's GCD never tries a candidate. It replaces the pair (a, b) with (b, a % b), a smaller pair with exactly the same common divisors, and stops when b is 0: then a is the answer. find_gcd only needs the two ends of nums, so it finds lo and hi and returns gcd(hi, lo).

🧱 The Analogy: Tiling a Floor With the Biggest Square

You want to cover a 8 x 3 floor with equal square tiles, as large as possible. Lay down 3 x 3 squares along the long side: two fit, and a 2 x 3 strip is left over. Whatever square tiles the whole floor must also tile that leftover strip, and the other way round, so the problem is now the 3 x 2 strip. One 2 x 2 square leaves a 1 x 2 strip, and 1 x 1 squares fill it exactly. The biggest square is 1 x 1, found in three cuts instead of trying every size. Each cut is one a % b.

🔑 Why It Works

a % b equals a - q * b for some whole number q. A number that divides a and b divides a - q * b; a number that divides b and a - q * b divides a. So gcd(a, b) == gcd(b, a % b) at every step, and when b reaches 0, gcd(a, 0) is simply a. The remainder is also small: whenever a >= b, a % b is less than half of a, so every two steps at least halve the pair. The one line that must be exact is the update: both new values come from the old pair, so a, b = b, a % b is a single statement.

  • Updating one value at a time: write a, b = b, a % b in one statement. a = b followed by b = a % b computes b % b == 0, so gcd(8, 3) returns 3 instead of 1.

  • Returning the wrong value: loop while b: and return a. The pair ends as (g, 0), so return b always gives 0.

  • Subtracting instead of taking the remainder: a - b again and again takes a / b steps (about 10^9 for gcd(109, 1)); % needs at most about 2 log2 of the smaller value.

  • The gcd of the wrong values: here it is min(nums) and max(nums) only. In [2,5,6,9,10] the answer is 2, while the gcd of all five values is 1.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

"Take its smallest value and its largest value", "return their greatest common divisor" and "the largest positive integer that divides both of them with no remainder": a common divisor of two whole numbers. That is the signal for Euclid's GCD: replace the pair by (b, a % b) until b is 0, instead of trying every divisor.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

The stopping decision: loop while b is not 0; the moment b == 0, return a, because gcd(a, 0) is a.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • The card's trap: a, b = b, a % b in one statement (gotcha 1: gcd(8, 3) for [7,5,6,8,3] would return 3).

  • The argument order does not matter: gcd(lo, hi) works too, because its first step computes lo % hi == lo and swaps the pair.

  • lo and hi can come from one loop instead of two calls to min and max; both are O(N), so pick whichever reads more clearly.

The 60-Second Interview Pitch

Say this out loud before you type a single line

I'd use Euclid's GCD. The problem only cares about the smallest and the largest value, so I find them in one pass each and run Euclid's algorithm on that pair. The idea is that a and b have exactly the same common divisors as b and a mod b, because a mod b is a minus a multiple of b. So I keep replacing the pair with b and a mod b until b is zero, and then a is the answer. The numbers at least halve every two steps, so the loop is logarithmic. The trap is the update: I write a comma b equals b comma a mod b as one statement, because setting a to b first would compute b mod b, which is always zero, and I'd return the smaller number. That's O(N plus log M) time and O(1) extra space.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N + log M)

min(nums) and max(nums) each read the N values once: O(N). Then gcd(hi, lo) runs while b:. Each step does one % and one swap. Whenever a >= b, a % b is less than half of a (if b <= a / 2 the remainder is below b; otherwise it is a - b, below a / 2), and two steps turn the pair's first value a into a % b. So the first value at least halves every two steps, and the loop runs at most about 2 * log2(M) times: O(log M). Total: O(N + log M).

SPACE COMPLEXITY

O(1)

find_gcd keeps lo and hi; gcd keeps a and b and loops instead of recursing, so no call stack grows: O(1). The answer is one integer.

Formal Recurrence Relation

T(N, M) = 2N (min and max) + 2 · log2(M) (remainder steps) = O(N + log M)

Derivation Progression

Find the two ends

O(N)

min(nums) and max(nums) each read every value once.

One remainder step

O(1)

a, b = b, a % b is one % and one swap.

Number of steps

O(log M)

Whenever a >= b, a % b < a / 2, and two steps turn a into a % b, so a at least halves every two steps.

Total

O(N + log M)

One pass for the ends, then a logarithmic number of constant-time steps.

Variable Definitions

NNN

Number of values, len(nums) (at most 1000)

MMM

The largest value, max(nums) (at most 1000)

Memory Architecture & Bounds

🟣 Call Stack

O(1): gcd loops instead of recursing

🔵 Auxiliary Heap

O(1): lo, hi, a, b

🟢 Output Space

O(1): one integer

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N): lo divides hi, so one remainder step ends the loop

Average Case

O(N+log⁡M)O(N + \log M)O(N+logM)

Worst Case

O(N+log⁡M)O(N + \log M)O(N+logM): consecutive Fibonacci numbers such as 610 and 987 take the most steps (14)

Pointer Invariant Transition Progression

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

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: "greatest common divisor", "the largest positive integer that divides both of them", "take its smallest value and its largest value". Two whole numbers and their largest shared divisor: Euclid's GCD, a, b = b, a % b until b is 0.

CONSTRAINTS & BOUNDS

At most 100010001000 values, each at most 100010001000: min and max are 200020002000 reads, and Euclid on two values up to 100010001000 takes at most 141414 remainder steps (consecutive Fibonacci numbers, 610610610 and 987987987). Trial division would need up to 100010001000 checks here, and 10910^9109 for values up to 10910^9109.

FAANG PRODUCTION TRAPS & EDGE CASES

With huge integers, as in cryptography, each % is itself a long division, so libraries use binary GCD or Lehmer's variant to cut its cost. With negative inputs, languages disagree on the sign of % (in Python it follows the divisor, in C and Java the dividend), so take absolute values first. A recursive gcd costs one stack frame per step; the loop never overflows.

Core Algorithmic State Invariants

  1. Zero Is the Neutral Start

gcd(x, 0) == x, so a running gcd over many values can start at 0 and fold each value in with g = gcd(g, x). Here only two values matter, but the same fold handles every value when a problem asks for the gcd of all of them.

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