Code Room
CodingHardcod-g826
Subject Modular arithmeticLevel Senior–Staff~40 minCommon in Algorithms & data structures interviewsIndustries Software development, Technology

Question

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.

Vibe coding: describe the solution in plain language (or narrate it) and the coach grades your approach. Generating runnable code from your description is coming next.

Run or narrate your approach, then ask the coach.