Extended Euclidean Algorithm - Problem

The Extended Euclidean Algorithm is a powerful mathematical tool that not only finds the gcd(a, b) but also determines integer coefficients x and y such that ax + by = gcd(a, b).

This algorithm is fundamental in number theory and has practical applications in cryptography, particularly for computing modular inverses. When gcd(a, m) = 1, the coefficient x gives us the modular inverse of a modulo m.

Task: Given two integers a and b, return a tuple [gcd, x, y] where gcd is the greatest common divisor and x, y are coefficients satisfying ax + by = gcd.

Note: If multiple solutions exist, return any valid solution.

Input & Output

Example 1 — Basic Case
$ Input: a = 30, b = 18
Output: [6, -1, 2]
💡 Note: gcd(30, 18) = 6, and we can verify: 30×(-1) + 18×2 = -30 + 36 = 6 ✓
Example 2 — Coprime Numbers
$ Input: a = 15, b = 28
Output: [1, -15, 8]
💡 Note: gcd(15, 28) = 1 (coprime), coefficients satisfy: 15×(-15) + 28×8 = -225 + 224 = -1, but we need |gcd| = 1
Example 3 — One Number is Zero
$ Input: a = 0, b = 12
Output: [12, 0, 1]
💡 Note: When a = 0, gcd(0, 12) = 12, and 0×0 + 12×1 = 12

Constraints

  • -109 ≤ a, b ≤ 109
  • At least one of a, b is non-zero

Visualization

Tap to expand
INPUTa30b18Find gcd(30, 18) andcoefficients x, y such that:30x + 18y = gcdALGORITHM1extgcd(30, 18): 30 = 1×18 + 122extgcd(18, 12): 18 = 1×12 + 63extgcd(12, 6): 12 = 2×6 + 04Base case: return (6, 1, 0)Backtrack with coefficients:Step 3: x=0, y=1-2×0=1 → (6,0,1)Step 2: x=1, y=0-1×1=-1 → (6,1,-1)Step 1: x=-1, y=1-1×(-1)=2 → (6,-1,2)RESULTGCD = 6x = -1y = 2Verification:30×(-1) + 18×2= -30 + 36 = 6 ✓Output Array:[6, -1, 2]Key Insight:The Extended Euclidean Algorithm tracks coefficient transformations duringrecursive GCD computation, solving both problems simultaneously in O(log n) time.TutorialsPoint - Extended Euclidean Algorithm | Recursive Coefficient Tracking
Asked in
Google 25 Microsoft 18 Amazon 15 Meta 12
28.4K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen