Sum of Decoded Numbers - Solution & Explanation
Problem Statement
You are given an integer array nums.
Each nums[i] is an encoded integer representing two positive integers xi and yi. To decode nums[i], define:
widthi = nums[i] % 10.di = floor(nums[i] / 10).xias the integer formed by the firstwidthidigits of the decimal representation ofdi.yias the integer formed by all remaining digits of the decimal representation ofdi.
It is guaranteed that the decimal representation of di contains more than widthi digits. Therefore, both xi and yi contain at least one digit.
The decoded value of nums[i] is xiyi.
Return the sum of the decoded values of all elements in nums, modulo 109 + 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, andy = 3. - The decoded value of 231 is
23 = 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, andy = 2. - The decoded value of 2522 is
252 = 625. - For 2101, we have
width = 1,d = 210,x = 2, andy = 10. - The decoded value of 2101 is
210 = 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, andy = 30. - The decoded value is
230 = 1073741824. - Therefore, the answer is
1073741824 modulo (109 + 7) = 73741817.
Constraints:
1 <= nums.length <= 105100 < nums[i] < 10151 <= widthi <= 91 <= xi, yi < 109- The digit sequences used to form
xiandyido not have leading zeros. - It is guaranteed that every element in
numsis a valid encoded integer.
Solution
We decode each element exactly as the statement describes. For each element v in nums, its width is w = v bmod 10, and the number left after dropping the last digit is d = \lfloor v / 10 \rfloor. Converting d to its decimal string s, the value x is the integer formed by the first w characters of s, and y is the integer formed by the remaining characters.
Since y can be as large as 10^9, multiplying repeatedly would be too slow, so we use fast power to compute x^y bmod (10^9 + 7) in O(log y) time, then accumulate the decoded values modulo 10^9 + 7.
The time complexity is O(n times log M), and the space complexity is O(log M). Here, n is the length of the array nums, and M is the maximum value in the array.
Code
Python
Java
C++
Go
TypeScript
Video Solution
LeetCode Weekly Contest 517 | 4038 & 4039 | Count Integers in a Block + Sum of Decoded Numbers | C++ • EdgeCaseOffByOne • 135 views views
Watch 4 more video solutions →Ready to solve this problem?
Practice Sum of Decoded Numbers with our built-in code editor and test cases.
Practice on FleetCodeProblem Info
Table of Contents
Practice this problem
Open in Editor