1438. Remainder Puzzle

Medium3.5 points estimatedNumber TheoryMaths

A lock opens at the smallest non-negative number x that leaves remainder remainders[i] when divided by moduli[i], for every index i. The moduli are not guaranteed to be pairwise coprime, so some systems have no solution. Return the smallest such x as a long, or -1 if no number satisfies every condition. Merge the conditions one at a time using the extended Euclidean algorithm; the least common multiple of all moduli is at most 10^9, but intermediate products can exceed 32 bits. The expected cost is O(k log M) time and O(1) extra space.

Example 1

Input:
remainders = [2,3,2], moduli = [3,5,7]
Output:
23
Explanation:

23 leaves remainders 2, 3 and 2 when divided by 3, 5 and 7, and nothing smaller does.

Example 2

Input:
remainders = [1,2], moduli = [2,4]
Output:
-1
Explanation:

The first condition forces x to be odd while the second forces x to be even, so there is no solution.

Constraints

1 ≤ k ≤ 10 (k is the length of both arrays)

1 ≤ moduli[i] ≤ 109

0 ≤ remainders[i] < moduli[i]

The least common multiple of all moduli is at most 109.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(k log M)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…