Double Modular Exponentiation - Problem
You are given a 2D array variables where each element variables[i] = [ai, bi, ci, mi] represents a set of parameters for a double modular exponentiation calculation, and an integer target.
Your task is to find all "good" indices. An index i is considered good if the following formula evaluates to the target:
((aibi % 10)ci) % mi == target
The calculation involves two levels of modular exponentiation:
- First, compute
aibi % 10(only the last digit matters) - Then, raise that result to the power of
ciand take modulomi
Return an array containing all good indices in any order.
Input & Output
example_1.py — Basic Case
$
Input:
variables = [[2,3,3,10],[3,3,3,1],[6,1,1,4]], target = 2
›
Output:
[0,2]
💡 Note:
For index 0: ((2³ % 10)³) % 10 = (8³) % 10 = 512 % 10 = 2 ✓. For index 1: ((3³ % 10)³) % 1 = (7³) % 1 = 0 ≠ 2. For index 2: ((6¹ % 10)¹) % 4 = (6¹) % 4 = 2 ✓.
example_2.py — Single Match
$
Input:
variables = [[39,3,1000,1000]], target = 17
›
Output:
[0]
💡 Note:
For index 0: ((39³ % 10)¹⁰⁰⁰) % 1000. First, 39³ = 59319, so 39³ % 10 = 9. Then 9¹⁰⁰⁰ % 1000 = 17.
example_3.py — No Matches
$
Input:
variables = [[1,1,1,1],[2,2,2,2]], target = 5
›
Output:
[]
💡 Note:
For index 0: ((1¹ % 10)¹) % 1 = 0 ≠ 5. For index 1: ((2² % 10)²) % 2 = ((4)²) % 2 = 0 ≠ 5. No indices satisfy the condition.
Visualization
Tap to expand
Understanding the Visualization
1
First Transformation
Calculate a^b % 10 to get the last digit of a^b
2
Second Transformation
Use the result as base for (result)^c % m
3
Target Matching
Compare final result with target to determine if index is good
Key Takeaway
🎯 Key Insight: Fast exponentiation reduces time complexity from O(b+c) to O(log b + log c) per calculation, making it essential for handling large exponents efficiently.
Time & Space Complexity
Time Complexity
O(n * log(max(b, c)))
For each of n variables, fast exponentiation takes O(log(exponent)) time
⚡ Linearithmic
Space Complexity
O(k)
Only store the result array where k is the number of good indices
✓ Linear Space
Constraints
- 1 ≤ variables.length ≤ 1000
- variables[i] = [ai, bi, ci, mi]
- 1 ≤ ai, bi, ci, mi ≤ 103
- 0 ≤ target ≤ 103
- The result array can be returned in any order
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code