#2961
Double Modular Exponentiation
MediumArrayMathSimulationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
This approach leverages the properties of modular arithmetic to compute results more efficiently. Instead of recalculating powers multiple times, we can simplify our calculations.
⚙️
Algorithm
6 steps- 1Step 1: Initialize an empty list to store good indices.
- 2Step 2: Loop through each index i in the variables array.
- 3Step 3: For each index, extract a, b, c, m from variables[i].
- 4Step 4: Compute the value using the formula (pow(a, b, 10) ** c) % m directly.
- 5Step 5: If the computed value equals the target, add i to the list of good indices.
- 6Step 6: Return the list of good indices.
solution.py15 lines
1# Full working Python code
2
3def find_good_indices(variables, target):
4 good_indices = []
5 for i in range(len(variables)):
6 a, b, c, m = variables[i]
7 value = (pow(a, b, 10) ** c) % m
8 if value == target:
9 good_indices.append(i)
10 return good_indices
11
12# Example usage
13variables = [[2,3,3,10],[3,3,3,1],[6,1,1,4]]
14target = 2
15print(find_good_indices(variables, target))ℹ
Complexity note: The time complexity remains O(n) since we still iterate through the list of variables once. The space complexity is O(1) as we are using a fixed amount of space for the output.
- 1Understanding modular arithmetic can simplify calculations.
- 2Recognizing that we can reduce the number of computations by using properties of exponents.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.