3079. Find the Sum of Encrypted Integers
Problem Description
You are given an integer array nums
containing positive integers. We define a function encrypt
such that encrypt(x)
replaces every digit in x
with the largest digit in x
. For example, encrypt(523) = 555
and encrypt(213) = 333
.
Return the sum of encrypted elements.
Intuition
To approach this problem, we need to simulate the encryption process as described. The idea is to implement a function encrypt(x)
which processes each integer x
and replaces its digits with the largest digit found within that number.
The steps to encrypt a number x
are:
- Extract Each Digit: Break down the number
x
to its digits. This can be done using modulus and integer division by 10 in a loop until the number is reduced to zero. - Identify the Largest Digit: As we extract digits, keep track of the maximum digit found, denoted as
mx
. - Form the Encrypted Number: For each digit in the original number, replace it with
mx
. Construct this new number by appendingmx
repeatedly to form111...1
of the same digit length as the original number. This is done by maintaining a base multiplierp
(starting at 1 and forming numbers like 1, 11, 111, etc.). - Compute the Final Sum: Once each number in the input array is encrypted, sum all these encrypted values to get the solution.
This approach efficiently transforms each element and keeps track of transformations to provide the correct sum of encrypted numbers.
Learn more about Math patterns.
Solution Approach
To solve this problem, we implement the function encrypt(x)
which simulates the encryption process for each number in the array nums
. The approach is as follows:
-
Define the Encrypt Function:
def encrypt(x: int) -> int: mx = p = 0 while x: x, v = divmod(x, 10) mx = max(mx, v) p = p * 10 + 1 return mx * p
- Extract Digits: The loop extracts each digit from
x
usingdivmod(x, 10)
, which dividesx
by 10 and provides both quotient and remainder. The remainderv
is a digit fromx
. - Track Maximum Digit:
mx
is updated to be the maximum of itself and the current digitv
. - Form Multiplier:
p
keeps record of the number of digits processed, forming numbers like1
,11
,111
, etc., which helps to reconstruct the encrypted number by multiplyingmx
.
- Extract Digits: The loop extracts each digit from
-
Calculate the Sum of Encrypted Elements:
return sum(encrypt(x) for x in nums)
- Each number in
nums
is passed throughencrypt(x)
and the encrypted versions are summed up using the built-insum
function.
- Each number in
This algorithm effectively performs the encryption by transforming each digit as required and then accumulates the results, using basic arithmetic and iteration constructs.
Ready to land your dream job?
Unlock your dream job with a 2-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's illustrate the solution approach using a small example.
Suppose we have the integer array nums = [523, 213]
.
Step-by-step Encryption Process:
-
Encrypt the First Number:
523
- Initialize
mx = 0
andp = 0
. - Extract digits from
523
:523 % 10 = 3
, updatemx = max(0, 3) = 3
, and updatep = p * 10 + 1 = 1
.52 % 10 = 2
, updatemx = max(3, 2) = 3
, and updatep = p * 10 + 1 = 11
.5 % 10 = 5
, updatemx = max(3, 5) = 5
, and updatep = p * 10 + 1 = 111
.
- As
523
is reduced to0
, the largest digitmx
is5
, andp
is111
. Multiply to get the encrypted number:5 * 111 = 555
.
- Initialize
-
Encrypt the Second Number:
213
- Initialize
mx = 0
andp = 0
. - Extract digits from
213
:213 % 10 = 3
, updatemx = max(0, 3) = 3
, and updatep = p * 10 + 1 = 1
.21 % 10 = 1
, updatemx = max(3, 1) = 3
, and updatep = p * 10 + 1 = 11
.2 % 10 = 2
, updatemx = max(3, 2) = 3
, and updatep = p * 10 + 1 = 111
.
- As
213
is reduced to0
, the largest digitmx
is3
, andp
is111
. Multiply to get the encrypted number:3 * 111 = 333
.
- Initialize
-
Calculate the Sum of Encrypted Elements:
- Encrypted numbers are
[555, 333]
. - Sum of encrypted numbers is
555 + 333 = 888
.
- Encrypted numbers are
Thus, the sum of the encrypted elements of the array nums = [523, 213]
is 888
. This example illustrates the encryption process of each element followed by summation of the results to obtain the final answer.
Solution Implementation
1from typing import List
2
3class Solution:
4 def sumOfEncryptedInt(self, nums: List[int]) -> int:
5 # Helper function to encrypt a single integer
6 def encrypt(x: int) -> int:
7 max_digit = 0 # Initialize the maximum digit found so far
8 place_value = 0 # Initialize the place value accumulator
9 while x:
10 x, current_digit = divmod(x, 10) # Divide x by 10, get quotient and current digit
11 # Update the maximum digit found
12 max_digit = max(max_digit, current_digit)
13 # Update place value by appending a 1
14 place_value = place_value * 10 + 1
15 # Return the encrypted value
16 return max_digit * place_value
17
18 # Compute and return the sum of encrypted integers in the list
19 return sum(encrypt(x) for x in nums)
20
1class Solution {
2 public int sumOfEncryptedInt(int[] nums) {
3 int ans = 0; // Initialize the sum of encrypted numbers.
4
5 // Loop through each number in the array.
6 for (int num : nums) {
7 ans += encrypt(num); // Add the encrypted value of the current number to the sum.
8 }
9
10 return ans; // Return the total sum of all encrypted numbers.
11 }
12
13 private int encrypt(int x) {
14 int maxDigit = 0; // Initialize the maximum digit found to 0.
15 int multiplier = 0; // Initialize the multiplier to create a series of 1s.
16
17 // Process the number one digit at a time.
18 while (x > 0) {
19 int currentDigit = x % 10; // Extract the last digit of the number.
20 maxDigit = Math.max(maxDigit, currentDigit); // Update the maximum digit.
21 multiplier = multiplier * 10 + 1; // Construct the multiplier, which is a series of 1s.
22 x /= 10; // Remove the last digit from the number by dividing by 10.
23 }
24
25 // Return the result of multiplying the maximum digit by the constructed multiplier.
26 return maxDigit * multiplier;
27 }
28}
29
1#include <vector>
2#include <algorithm>
3
4class Solution {
5public:
6 int sumOfEncryptedInt(std::vector<int>& nums) {
7 // Lambda function to encrypt a single integer
8 auto encrypt = [&](int x) {
9 int maxDigit = 0; // Variable to store the maximum digit in the number
10 int digitMultiplier = 0; // Variable to calculate the multiplier based on number of digits
11
12 // Process each digit of the number
13 while (x > 0) {
14 int currentDigit = x % 10; // Get the last digit of the number
15 maxDigit = std::max(maxDigit, currentDigit); // Update maxDigit if currentDigit is larger
16 digitMultiplier = digitMultiplier * 10 + 1; // Update multiplier with a 1 appended to it
17 x /= 10; // Remove the last digit from number
18 }
19
20 // Return the encrypted value: maxDigit multiplied by the digitMultiplier
21 return maxDigit * digitMultiplier;
22 };
23
24 int sum = 0; // Initialize sum of encrypted integers to zero
25
26 // Iterate through all numbers and add their encrypted values to sum
27 for (int number : nums) {
28 sum += encrypt(number);
29 }
30
31 return sum; // Return the sum of encrypted integers
32 }
33};
34
1// Function to calculate the sum of encrypted integers from an array
2function sumOfEncryptedInt(nums: number[]): number {
3 // Encrypt function to transform a single number
4 const encrypt = (x: number): number => {
5 let mx = 0; // Variable to store the maximum digit found
6 let p = 0; // Variable to store the pattern based on maximum digit count
7
8 // Loop through each digit of the number
9 while (x > 0) {
10 // Update the maximum digit found so far
11 mx = Math.max(mx, x % 10);
12 // Construct the pattern by increasing the power of ten
13 p = p * 10 + 1;
14 // Move to the next digit
15 x = Math.floor(x / 10);
16 }
17
18 // Return the encrypted value by multiplying maximum digit and pattern
19 return mx * p;
20 };
21
22 // Use reduce to accumulate the encrypted sum of all numbers in the array
23 return nums.reduce((accumulator, currentValue) => accumulator + encrypt(currentValue), 0);
24}
25
Time and Space Complexity
The time complexity of the given code is O(n \times \log M)
, where n
is the length of the nums
list, and M
is the maximum integer value in the list. This is because the encrypt
function processes each digit of an integer, and the number of digits in the worst case is O(\log M)
. The outer loop iterates through each number in the list, leading to the overall complexity.
The space complexity is O(1)
. The function uses a constant amount of additional space, regardless of the size of the input list nums
, because no data structures that grow with the input size are used.
Learn more about how to find time and space complexity quickly.
The three-steps of Depth First Search are:
- Identify states;
- Draw the state-space tree;
- DFS on the state-space tree.
Recommended Readings
Math for Technical Interviews How much math do I need to know for technical interviews The short answer is about high school level math Computer science is often associated with math and some universities even place their computer science department under the math faculty However the reality is that you
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https algomonster s3 us east 2 amazonaws com recursion jpg You first
Want a Structured Path to Master System Design Too? Don’t Miss This!