Sum of Decoded Numbers Problem
Description
LeetCode Problem 4039.
You are given an integer array nums.
Each nums[i] is an encoded integer representing two positive integers x_i and y_i. To decode nums[i], define:
width_i = nums[i] % 10.d_i = floor(nums[i] / 10).x_ias the integer formed by the firstwidth_idigits of the decimal representation ofd_i.y_ias the integer formed by all remaining digits of the decimal representation ofd_i.
It is guaranteed that the decimal representation of d_i contains more than width_i digits. Therefore, both x_i and y_i contain at least one digit.
The decoded value of nums[i] is x_i^yi.
Return the sum of the decoded values of all elements in nums, modulo 10^9 + 7.
The floor() function returns the integer part of the division.
Example 1:
Input: nums = [231]
Output: 8
Explanation:
- For 231, we have width = 1, d = 23, x = 2, and y = 3.
- The decoded value of 231 is 2^3 = 8.
- Since there is only one element in nums, the sum of the decoded values is 8.
Example 2:
Input: nums = [2522,2101]
Output: 1649
Explanation:
- For 2522, we have width = 2, d = 252, x = 25, and y = 2.
- The decoded value of 2522 is 25^2 = 625.
- For 2101, we have width = 1, d = 210, x = 2, and y = 10.
- The decoded value of 2101 is 2^10 = 1024.
- The sum of the decoded values is 625 + 1024 = 1649.
Example 3:
Input: nums = [2301]
Output: 73741817
Explanation:
- For 2301, we have width = 1, d = 230, x = 2, and y = 30.
- The decoded value is 2^30 = 1073741824.
- Therefore, the answer is 1073741824 modulo (10^9 + 7) = 73741817.
Constraints:
1 <= nums.length <= 10^5100 < nums[i] < 10^151 <= width_i <= 91 <= x_i, y_i < 10^9- The digit sequences used to form
x_iandy_ido not have leading zeros. - It is guaranteed that every element in
numsis a valid encoded integer.
Solution
Approach: Simulation + fast exponentiation
Decode every element as the statement says. For v in nums, the width is w = v % 10 and d = v / 10 (integer division). Write d as a decimal string s: x is the number formed by the first w characters of s, and y the number formed by the rest.
y can be close to 10^9, so multiplying x by itself y times is too slow. Compute x^y mod (10^9 + 7) by fast exponentiation in O(log y) and add the results modulo 10^9 + 7.
Complexity: time O(n log M), space O(log M), where n = nums.length and M is the largest value.
class Solution:
def sumDecoded(self, nums: List[int]) -> int:
mod = 10**9 + 7
ans = 0
for v in nums:
d, w = divmod(v, 10)
s = str(d)
x = int(s[:w])
y = int(s[w:])
ans = (ans + pow(x, y, mod)) % mod
return ans