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:

  1. First, compute aibi % 10 (only the last digit matters)
  2. Then, raise that result to the power of ci and take modulo mi

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
Double Modular Exponentiation ProcessInputa = 2, b = 3c = 3, m = 10target = 2Step 1a^b % 102³ % 10= 8Step 2(result)^c % m8³ % 10= 2Result2 == targetGood Index! ✓Key Insight: Fast ExponentiationInstead of multiplying 2×2×2 (3 operations)Use binary exponentiation: 2¹ → 2² → 2³ (log n operations)This optimization is crucial for large exponents!
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

n
2n
Linearithmic
Space Complexity
O(k)

Only store the result array where k is the number of good indices

n
2n
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
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
28.0K Views
Medium Frequency
~15 min Avg. Time
850 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