Code RoomDiscrete logarithm modulo prime
HardPrep Room Coding #1389

Discrete logarithm modulo prime

CodingAlgorithms & data structuresSenior–Staff~40 min

Given a prime p and integers a, b, find the smallest non-negative integer x such that a^x is congruent to b modulo p, or return -1 if no such x exists. Assume p is prime and a is not a multiple of p. A linear scan over all exponents is too slow when p is large, so use the baby-step giant-step (meet-in-the-middle) algorithm running in O(sqrt(p)). Return 0 when b is congruent to 1 (since a^0 = 1).

Implement
discrete_log(a: int, b: int, p: int) → int
Examples
in[2,3,5]out3
What a strong answer looks like

State your approach and its time/space complexity out loud before you optimize. Handle the edge cases (empty input, duplicates, overflow), and say why you chose this over the brute force. Green tests are the floor, not the grade.

0:00 of about 40 min
InputExpectedGot
[2,3,5]3not run yetsample