Double Modular Exponentiation - Problem

You are given a 0-indexed 2D array variables where variables[i] = [ai, bi, ci, mi], and an integer target.

An index i is good if the following formula holds:

((aibi % 10)ci) % mi == target

Return an array consisting of good indices in any order.

Input & Output

Example 1 — Basic Case
$ Input: variables = [[2,3,3,10],[3,1,4,12],[7,3,1,17],[4,2,5,5]], target = 3
Output: [2]
💡 Note: For index 2: ((7³ % 10)¹) % 17 = (343 % 10)¹ % 17 = 3¹ % 17 = 3. Only index 2 matches target 3.
Example 2 — Multiple Matches
$ Input: variables = [[39,3,1000,1000]], target = 49
Output: [0]
💡 Note: For index 0: ((39³ % 10)¹⁰⁰⁰) % 1000 = (59319 % 10)¹⁰⁰⁰ % 1000 = 9¹⁰⁰⁰ % 1000 = 49.
Example 3 — No Matches
$ Input: variables = [[2,2,2,2]], target = 5
Output: []
💡 Note: For index 0: ((2² % 10)²) % 2 = (4²) % 2 = 16 % 2 = 0 ≠ 5. No indices match.

Constraints

  • 1 ≤ variables.length ≤ 1000
  • variables[i] = [ai, bi, ci, mi]
  • 1 ≤ ai, bi, ci, mi ≤ 106
  • 0 ≤ target ≤ 106

Visualization

Tap to expand
Double Modular Exponentiation INPUT variables array (4 elements): i=0: [2, 3, 3, 10] a=2, b=3, c=3, m=10 i=1: [3, 1, 4, 12] a=3, b=1, c=4, m=12 i=2: [7, 3, 1, 17] a=7, b=3, c=1, m=17 i=3: [4, 2, 5, 5] a=4, b=2, c=5, m=5 target = 3 Formula to check: ((a^b % 10)^c) % m == target ALGORITHM STEPS 1 Compute a^b % 10 Use fast modular exponent temp1 = pow(a,b) mod 10 2 Compute temp1^c % m Second modular exponent result = pow(temp1,c) mod m 3 Compare with target Check if result == target if (result == 3) add index 4 Collect good indices Return matching indices i=0: (2^3%10)^3%10 = 8^3%10 = 2 i=1: (3^1%10)^4%12 = 3^4%12 = 9 i=2: (7^3%10)^1%17 = 3^1%17 = 3 OK i=3: (4^2%10)^5%5 = 6^5%5 = 1 Only i=2 equals target=3 FINAL RESULT Good indices found: [2] Verification for i=2 a=7, b=3, c=1, m=17 7^3 = 343 343 % 10 = 3 3^1 % 17 = 3 3 == target(3) -- OK Output: [2] Key Insight: Modular exponentiation computes (base^exp) % mod efficiently in O(log exp) time using repeated squaring. The nested structure ((a^b % 10)^c) % m requires two modular exponentiations per element, keeping intermediate values small to prevent overflow. TutorialsPoint - Double Modular Exponentiation | Optimized Modular Exponentiation
Asked in
Google 15 Amazon 12 Microsoft 8
23.5K Views
Medium Frequency
~25 min Avg. Time
890 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