Double Modular Exponentiation — LeetCode 2961 Python Solution
- Problem
- #2961
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The 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: 0 <= i < variables.length ((aibi % 10)ci) % mi == target Return an array consisting of good indices in any order.
Example
- Input
- variables = [[2,3,3,10],[3,3,3,1],[6,1,1,4]], target = 2
- Output
- [0,2]
- Explanation
- For each index i in the variables array:
Python solution
class Solution:
def getGoodIndices(self, variables: List[List[int]], target: int) -> List[int]:
return [
i
for i, (a, b, c, m) in enumerate(variables)
if pow(pow(a, b, 10), c, m) == target
]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log M), where n is the length of the array variables; and M is the maximum value in b_i and c_i, in this problem M \le 10^3 |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2961. Double Modular Exponentiation is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2961. Double Modular Exponentiation?
- LeetCode 2961. Double Modular Exponentiation is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2961. Double Modular Exponentiation?
- The Python solution on this page runs in O(n \times \log M), where n is the length of the array variables; and M is the maximum value in b_i and c_i, in this problem M \le 10^3.
- What is the space complexity of LeetCode 2961. Double Modular Exponentiation?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2961. Double Modular Exponentiation cover?
- LeetCode 2961. Double Modular Exponentiation is tagged Array, Math and Simulation on LeetCode.