Taro Logo

Double Modular Exponentiation

#1 Most AskedMedium
1 view
Topics:
Arrays

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 1:

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:
1) For the index 0, variables[0] = [2,3,3,10], (23 % 10)3 % 10 = 2.
2) For the index 1, variables[1] = [3,3,3,1], (33 % 10)3 % 1 = 0.
3) For the index 2, variables[2] = [6,1,1,4], (61 % 10)1 % 4 = 2.
Therefore we return [0,2] as the answer.

Example 2:

Input: variables = [[39,3,1000,1000]], target = 17
Output: []
Explanation: For each index i in the variables array:
1) For the index 0, variables[0] = [39,3,1000,1000], (393 % 10)1000 % 1000 = 1.
Therefore we return [] as the answer.

Constraints:

  • 1 <= variables.length <= 100
  • variables[i] == [ai, bi, ci, mi]
  • 1 <= ai, bi, ci, mi <= 103
  • 0 <= target <= 103

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the constraints and data types for the integers $a$, $b$, $c$, $m$, and the target?
  2. Should the returned list of indices be in ascending order, or does the order not matter?
  3. What should be returned if no set of variables satisfies the condition and results in the target?
  4. Can the input array of variables be empty, and how should we handle such a case?
  5. Are $b$ or $c$ guaranteed to be non-negative, or could we encounter negative exponents?

Brute Force Solution

Approach

The brute force approach to solving this problem involves checking every single item from the given list one by one. For every single item, we perform the exact mathematical calculations requested by the rules to see if it matches the target value we are looking for.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at the very first item in the list of numbers.
  2. Take the first part of the item and raise it to the power of the second part, then divide it by ten and keep just the remainder.
  3. Take that remainder and raise it to the power of the third part, then divide it by ten again and find the new remainder.
  4. Check if this final resulting number matches the target goal given in the problem.
  5. If it matches, save this item's position as one of the answers.
  6. Move on to the next item in the list and repeat the entire mathematical calculation process from the beginning.
  7. Continue this exact checking process for every single item until you have gone through the entire list.
  8. Gather all the items that successfully matched the target and present them as the final result.

Code Implementation

def get_good_indices(variables, target):    matching_indices = []    # Iterate through every item to evaluate the mathematical rules for each configuration independently    for current_index in range(len(variables)):        base_value, exponent_first, exponent_second, modulo_value = variables[current_index]        first_stage_result = pow(base_value, exponent_first, 10)        final_result = pow(first_stage_result, exponent_second, modulo_value)        # Check if the calculated value matches the target goal to determine if we should save the position        if final_result == target:            matching_indices.append(current_index)    return matching_indices

Big(O) Analysis

Time Complexity
O(n) – We iterate through the list of n items one by one from the beginning to the very end. For every single item, we perform a fixed sequence of arithmetic operations involving modulo exponentiation. Since the mathematical calculation for each item takes constant time regardless of the input size, the total cost is driven solely by processing all n items in the list. This leads to approximately n operations, which simplifies to O(n).
Space Complexity
O(N) – To satisfy the requirement of gathering all successful items, we must allocate an auxiliary dynamic list to store the indices of the matching elements. In the worst-case scenario where every item in the input list of size N meets the target condition, this resulting list will store N indices. Therefore, the extra memory required scales linearly with the number of input items. No other data structures are used, as the mathematical operations are performed using a constant number of primitive variables. This leads to an overall auxiliary space complexity of O(N).

Optimal Solution

Approach

Instead of doing massive, complex math multiplications that take forever and overwhelm standard calculators, the optimal approach breaks the calculations down into smaller, manageable chunks. By applying a mathematical shortcut repeatedly at every step, we keep the numbers small and lightning-fast.

Here's how the algorithm would work step-by-step:

  1. Look at the first group of numbers provided in the problem and focus on the first part of the math equation.
  2. Instead of multiplying the base number by itself a massive number of times all at once, multiply it just once and immediately apply the division rule to keep the resulting number small.
  3. Take that smaller, controlled result and repeat the multiplication process just a few more times, shrinking the result back down using the division rule after every single step.
  4. Once you finish that initial part of the equation, take that final small result and use it as the power for the next layer of the math puzzle.
  5. Repeat the exact same trick for this new layer: multiply in small steps and shrink the number down continuously using the division rule.
  6. Keep track of which starting items meet the final target goal by checking them one by one.
  7. Gather all the qualifying items together to form your final answer.

Code Implementation

class Solution:
    def get_good_indices(self, variables: list[list[int]], target_modulo: int) -> list[int]:
        good_indices_list = []
        
        # We iterate through every variable set to evaluate its compliance with the condition.
        for index_counter, current_variable in enumerate(variables):
            base_value, exponent_value, inner_modulo, target_value = current_variable
            
            first_layer_result = pow(base_value, exponent_value, 10)
            
            # We compute the double modular exponentiation step by step to avoid overflow.
            final_layer_result = pow(first_layer_result, inner_modulo, target_modulo)
            
            if final_layer_result == target_value:
                good_indices_list.append(index_counter)
                
        # We return all indices that successfully match the target value criteria.
        return good_indices_list

Big(O) Analysis

Time Complexity
O(n log b) – To solve the double modular exponentiation problem, we iterate through each of the n items in the input list and apply modular exponentiation twice. Each modular exponentiation step uses binary exponentiation, which takes logarithmic time proportional to the value of the exponents. Therefore, the cost is driven by checking n items where each item performs logarithmic multiplications. This operations count approximates n times log b, which simplifies to the final Big O time complexity of O(n log b).
Space Complexity
O(k) – We collect the indices of all qualifying items into a dynamic list to form the final answer. Assuming there are N total items and K of them meet the target goal, this result list requires auxiliary space proportional to K. Since K can be at most N in the worst-case scenario, the space complexity simplifies to Big O of N. Beyond this output list, the modular exponentiation calculations use only a few constant-space scalar variables for loops and intermediate math steps.

Edge Cases

Empty variables array
How to Handle:
Return an empty list immediately since no indices can satisfy the condition.
Exponent values such as b or c equal to zero
How to Handle:
Any base raised to the power of zero correctly evaluates to 1 according to mathematical rules.
Modulus m equal to 1
How to Handle:
The final modulo operation by 1 will always yield 0, which correctly simplifies the calculation.
Very large base and exponent values causing integer overflow
How to Handle:
Use modular exponentiation algorithms and built-in big integer types to prevent overflow issues.
All variables resulting in values that never match the target
How to Handle:
The result list remains empty and is returned without any erroneous indices.
Multiple sets of variables producing the same target value
How to Handle:
Collect all matching indices into the result list in the exact order they appear.
Target value greater than any possible computed modular result
How to Handle:
No variables will match the target and an empty array will be returned.
Maximum constraints on array length and integer values
How to Handle:
Ensure the time complexity remains optimal by avoiding redundant recomputations for each variable set.
0/18 completed