algoadvance

Leetcode 372. Super Pow

Problem Statement

In this problem, you are given two positive integers a and an array of positive integers b which represents a very large integer. You need to calculate the result of a^b modulo 1337.

Specifically, you are to implement a function superPow, which is defined as follows:

public int superPow(int a, int[] b)

The result should be a raised to the power represented by the array b modulo 1337.

Examples

  1. Input: a = 2, b = [3] Output: 8
  2. Input: a = 2, b = [1,0] Output: 1024

Clarifying Questions

  1. Q: What is the range of values for a and the elements of b?
    A: a is a positive integer up to 2^31 - 1. Elements of b range from 0 to 9.

  2. Q: How large can the array b be?
    A: b can have up to 200 elements.

  3. Q: Can a or b have any leading zeros in the array?
    A: No, a will not have leading zeros and b will not have leading elements in the array.

Strategy

To solve this problem, we need to use modular exponentiation to manage the large powers efficiently. Here’s the step-by-step plan:

  1. Modular exponentiation(): Since a and b can be very large, we can use properties of modular arithmetic to simplify the computation.
  2. Decompose the array b: Break down b into smaller parts and compute the corresponding powers of a modulo 1337.
  3. Combining the results: Use the property (a^m * a^n) % k = ( (a^m % k) * (a^n % k) ) % k.

Specifically, we can recursively reduce the problem using:

We will use a helper function to manage the recursive breakdown of the problem and use the modulus properties effectively.

Code

public class Solution {
    private static final int MOD = 1337;

    public int superPow(int a, int[] b) {
        return superPowHelper(a, b, b.length - 1);
    }

    private int superPowHelper(int a, int[] b, int idx) {
        if (idx == -1) {
            return 1;
        }
        int lastDigit = b[idx];
        
        int part1 = myPow(a, lastDigit);
        int part2 = myPow(superPowHelper(a, b, idx - 1), 10);
        
        return part1 * part2 % MOD;
    }

    private int myPow(int a, int k) {
        a %= MOD;
        int result = 1;
        for (int i = 0; i < k; i++) {
            result = result * a % MOD;
        }
        return result;
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        System.out.println(sol.superPow(2, new int[]{3}));          // Output: 8
        System.out.println(sol.superPow(2, new int[]{1, 0}));       // Output: 1024
        System.out.println(sol.superPow(2, new int[]{1, 0, 2, 4})); // Output might vary but you can predict as needed.
    }
}

Time Complexity

This ensures the solution is efficient given the constraints.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI