3079. Find the Sum of Encrypted Integers
Problem Description
You are given an integer array nums
containing positive integers. You need to apply an encryption function to each element and return the sum of all encrypted values.
The encryption function encrypt(x)
works by replacing every digit in the integer x
with the largest digit found in x
.
For example:
encrypt(523) = 555
because the largest digit in 523 is 5, so all digits (5, 2, 3) are replaced with 5encrypt(213) = 333
because the largest digit in 213 is 3, so all digits (2, 1, 3) are replaced with 3
The task is to:
- Apply the encryption function to each element in the array
- Sum all the encrypted values
- Return the total sum
The solution implements this by:
- Creating an
encrypt
function that finds the maximum digit in a number while tracking the number of digits - For each number, it extracts digits using modulo 10 and integer division
- It keeps track of the maximum digit (
mx
) and builds a placeholder value (p
) like 1, 11, 111, etc. - The encrypted value is calculated as
mx * p
, which effectively replaces all digits with the maximum digit - Finally, it returns the sum of all encrypted values using a generator expression
Intuition
The key insight is recognizing that encrypting a number means creating a new number with the same number of digits, where all digits are replaced by the maximum digit from the original number.
To achieve this transformation, we need two pieces of information:
- The maximum digit in the number
- How many digits the number has
Once we have these, we can construct the encrypted number. For instance, if we know the maximum digit is 7 and the number has 3 digits, the encrypted result would be 777.
The clever part of the solution is how it builds the result. Instead of converting to a string or counting digits separately, we can extract digits and count them in a single pass through the number. As we process each digit through divmod(x, 10)
:
- We compare and update the maximum digit
- We build a "pattern" number
p
that grows as 1, 11, 111, 1111, etc.
This pattern number p
serves as a multiplier. When we multiply the maximum digit by this pattern (like 5 * 111 = 555
), we get exactly what we want - the same digit repeated for the correct number of positions.
The beauty of this approach is its efficiency: we traverse the digits only once, avoid string conversions, and use simple arithmetic operations to construct the encrypted value directly.
Learn more about Math patterns.
Solution Approach
The solution implements a simulation approach with a helper function encrypt(x)
that processes each number in the array.
Implementation walkthrough:
-
Define the encrypt function: The function takes an integer
x
and returns its encrypted form. -
Initialize variables:
mx = 0
: Tracks the maximum digit found in the numberp = 0
: Builds the pattern number (1, 11, 111, ...)
-
Extract and process digits: Using a while loop that continues until
x
becomes 0:x, v = divmod(x, 10)
: This simultaneously gets the last digitv
and removes it fromx
mx = max(mx, v)
: Update the maximum digit if current digit is largerp = p * 10 + 1
: Build the pattern by shifting left and adding 1
-
Calculate encrypted value: Return
mx * p
- This multiplication creates a number where all digits are the maximum digit
- For example: if
mx = 5
andp = 111
, then5 * 111 = 555
-
Sum all encrypted values: Use a generator expression
sum(encrypt(x) for x in nums)
to:- Apply the encrypt function to each element in the array
- Sum all the encrypted results
- Return the final sum
Example trace for encrypt(523)
:
- Initial:
x = 523
,mx = 0
,p = 0
- Iteration 1:
v = 3
,x = 52
,mx = 3
,p = 1
- Iteration 2:
v = 2
,x = 5
,mx = 3
,p = 11
- Iteration 3:
v = 5
,x = 0
,mx = 5
,p = 111
- Return:
5 * 111 = 555
The time complexity is O(n * m)
where n
is the length of the array and m
is the average number of digits per number. The space complexity is O(1)
as we only use a constant amount of extra space.
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through the solution with nums = [523, 213, 82]
.
Step 1: Encrypt first number (523)
- Start with
x = 523
,mx = 0
,p = 0
- Extract rightmost digit:
523 ÷ 10 = 52
remainder3
- Update:
x = 52
,v = 3
,mx = 3
,p = 1
- Update:
- Extract next digit:
52 ÷ 10 = 5
remainder2
- Update:
x = 5
,v = 2
,mx = 3
,p = 11
- Update:
- Extract last digit:
5 ÷ 10 = 0
remainder5
- Update:
x = 0
,v = 5
,mx = 5
,p = 111
- Update:
- Calculate encrypted value:
5 × 111 = 555
Step 2: Encrypt second number (213)
- Start with
x = 213
,mx = 0
,p = 0
- Extract rightmost digit:
213 ÷ 10 = 21
remainder3
- Update:
x = 21
,v = 3
,mx = 3
,p = 1
- Update:
- Extract next digit:
21 ÷ 10 = 2
remainder1
- Update:
x = 2
,v = 1
,mx = 3
,p = 11
- Update:
- Extract last digit:
2 ÷ 10 = 0
remainder2
- Update:
x = 0
,v = 2
,mx = 3
,p = 111
- Update:
- Calculate encrypted value:
3 × 111 = 333
Step 3: Encrypt third number (82)
- Start with
x = 82
,mx = 0
,p = 0
- Extract rightmost digit:
82 ÷ 10 = 8
remainder2
- Update:
x = 8
,v = 2
,mx = 2
,p = 1
- Update:
- Extract last digit:
8 ÷ 10 = 0
remainder8
- Update:
x = 0
,v = 8
,mx = 8
,p = 11
- Update:
- Calculate encrypted value:
8 × 11 = 88
Step 4: Sum all encrypted values
- Total =
555 + 333 + 88 = 976
The key insight is how the pattern number p
(1, 11, 111...) acts as a multiplier. When we multiply the maximum digit by this pattern, we get a number with all digits replaced by that maximum digit. The solution efficiently builds this pattern while finding the maximum digit in a single pass through each number.
Solution Implementation
1class Solution:
2 def sumOfEncryptedInt(self, nums: List[int]) -> int:
3 """
4 Calculate the sum of encrypted integers from the input list.
5
6 Args:
7 nums: List of integers to be encrypted and summed
8
9 Returns:
10 Sum of all encrypted integers
11 """
12
13 def encrypt(number: int) -> int:
14 """
15 Encrypt a single integer by replacing all digits with the maximum digit.
16
17 The encryption process:
18 1. Find the maximum digit in the number
19 2. Replace all digits with this maximum digit
20
21 Args:
22 number: Integer to encrypt
23
24 Returns:
25 Encrypted integer with all digits replaced by the maximum digit
26 """
27 max_digit = 0 # Track the maximum digit found
28 place_value_pattern = 0 # Build a pattern like 111 for a 3-digit number
29
30 # Process each digit from right to left
31 while number > 0:
32 # Extract the rightmost digit using divmod
33 number, current_digit = divmod(number, 10)
34
35 # Update the maximum digit if current digit is larger
36 max_digit = max(max_digit, current_digit)
37
38 # Build the place value pattern (e.g., 1, 11, 111, ...)
39 place_value_pattern = place_value_pattern * 10 + 1
40
41 # Return the encrypted number: max_digit repeated for each digit position
42 return max_digit * place_value_pattern
43
44 # Calculate and return the sum of all encrypted numbers
45 return sum(encrypt(num) for num in nums)
46
1class Solution {
2 /**
3 * Calculates the sum of encrypted values for all integers in the array.
4 *
5 * @param nums The input array of integers to be encrypted and summed
6 * @return The sum of all encrypted integers
7 */
8 public int sumOfEncryptedInt(int[] nums) {
9 int sum = 0;
10
11 // Iterate through each number in the array
12 for (int number : nums) {
13 // Add the encrypted value of current number to the sum
14 sum += encrypt(number);
15 }
16
17 return sum;
18 }
19
20 /**
21 * Encrypts an integer by replacing all digits with the maximum digit.
22 * For example: encrypt(523) = 555, encrypt(213) = 333
23 *
24 * @param x The integer to be encrypted
25 * @return The encrypted integer with all digits replaced by the maximum digit
26 */
27 private int encrypt(int x) {
28 int maxDigit = 0; // Stores the maximum digit found in x
29 int placeValue = 0; // Builds a number with same digit count (e.g., 111 for 3-digit number)
30
31 // Extract digits from right to left
32 while (x > 0) {
33 // Get the rightmost digit
34 int currentDigit = x % 10;
35
36 // Update maximum digit if current is larger
37 maxDigit = Math.max(maxDigit, currentDigit);
38
39 // Build place value pattern (1, 11, 111, etc.)
40 placeValue = placeValue * 10 + 1;
41
42 // Remove the rightmost digit
43 x = x / 10;
44 }
45
46 // Return the encrypted number (max digit repeated for each position)
47 return maxDigit * placeValue;
48 }
49}
50
1class Solution {
2public:
3 int sumOfEncryptedInt(vector<int>& nums) {
4 // Lambda function to encrypt a single integer
5 auto encrypt = [&](int number) {
6 int maxDigit = 0; // Track the maximum digit in the number
7 int digitPattern = 0; // Build a pattern like 111 for 3-digit numbers
8
9 // Process each digit of the number from right to left
10 while (number > 0) {
11 // Extract the rightmost digit and update maximum
12 maxDigit = max(maxDigit, number % 10);
13
14 // Build the digit pattern (1, 11, 111, etc.)
15 digitPattern = digitPattern * 10 + 1;
16
17 // Remove the rightmost digit
18 number /= 10;
19 }
20
21 // Encryption result: multiply max digit by the pattern
22 // Example: if maxDigit=7 and digitPattern=111, result=777
23 return maxDigit * digitPattern;
24 };
25
26 int totalSum = 0; // Initialize sum of all encrypted numbers
27
28 // Iterate through each number in the input array
29 for (int currentNumber : nums) {
30 // Add the encrypted value to the total sum
31 totalSum += encrypt(currentNumber);
32 }
33
34 return totalSum;
35 }
36};
37
1/**
2 * Calculates the sum of encrypted integers in an array
3 * @param nums - Array of positive integers to be encrypted and summed
4 * @returns The sum of all encrypted integers
5 */
6function sumOfEncryptedInt(nums: number[]): number {
7 /**
8 * Encrypts a single integer by replacing all digits with the maximum digit
9 * @param x - The integer to encrypt
10 * @returns The encrypted integer
11 */
12 const encrypt = (x: number): number => {
13 let maxDigit: number = 0;
14 let positionMultiplier: number = 0;
15
16 // Extract digits from right to left, finding the maximum digit
17 // and building a multiplier with the same number of digits (e.g., 111 for 3-digit numbers)
18 while (x > 0) {
19 // Get the rightmost digit
20 const currentDigit: number = x % 10;
21
22 // Update maximum digit found so far
23 maxDigit = Math.max(maxDigit, currentDigit);
24
25 // Build the position multiplier (1, 11, 111, etc.)
26 positionMultiplier = positionMultiplier * 10 + 1;
27
28 // Remove the rightmost digit
29 x = Math.floor(x / 10);
30 }
31
32 // Return the encrypted value (max digit repeated for each position)
33 return maxDigit * positionMultiplier;
34 };
35
36 // Sum all encrypted values using reduce
37 return nums.reduce((accumulator: number, currentValue: number) => {
38 return accumulator + encrypt(currentValue);
39 }, 0);
40}
41
Time and Space Complexity
Time Complexity: O(n × log M)
The algorithm iterates through each number in the nums
array (n elements). For each number, the encrypt
function processes the digits by repeatedly dividing by 10 until the number becomes 0. The number of iterations in the while loop equals the number of digits in the number, which is O(log₁₀ x)
for a number x. In the worst case, x can be the maximum value M in the array, giving us O(log M)
operations per number. Therefore, the total time complexity is O(n × log M)
.
Space Complexity: O(1)
The algorithm uses only a constant amount of extra space. The encrypt
function uses a fixed number of variables (mx
, p
, x
, v
) regardless of the input size. The sum operation and generator expression don't create additional data structures that scale with input size, maintaining constant space usage throughout the execution.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Handling Zero as Input
The current implementation doesn't handle the edge case where the input number is 0. When number = 0
, the while loop never executes, resulting in place_value_pattern = 0
and returning 0 * 0 = 0
. However, the correct encryption of 0 should still be 0 (single digit with value 0).
Fix:
def encrypt(number: int) -> int:
# Handle zero as a special case
if number == 0:
return 0
max_digit = 0
place_value_pattern = 0
while number > 0:
number, current_digit = divmod(number, 10)
max_digit = max(max_digit, current_digit)
place_value_pattern = place_value_pattern * 10 + 1
return max_digit * place_value_pattern
2. Integer Overflow for Large Numbers
When dealing with very large numbers or arrays with many large elements, the multiplication max_digit * place_value_pattern
and the final sum could potentially cause integer overflow in languages with fixed integer sizes. While Python handles arbitrary precision integers automatically, this could be an issue when porting to other languages.
Mitigation Strategy:
- Be aware of integer limits in the target language
- Consider using long/BigInteger types where necessary
- Add validation for maximum input sizes if needed
3. Inefficient String Conversion Alternative
A common alternative approach might be converting the number to a string to find digits:
def encrypt(number: int) -> int:
str_num = str(number)
max_digit = max(int(d) for d in str_num)
return int(str(max_digit) * len(str_num))
While this works and is more readable, it's less efficient due to string conversions and allocations. The mathematical approach in the original solution is more performant.
4. Forgetting to Handle Negative Numbers
The problem states "positive integers", but if the constraints change or input validation is needed, negative numbers would break the current logic. The modulo operation with negative numbers behaves differently, and the encryption concept would need redefinition.
Defensive Programming:
def encrypt(number: int) -> int:
# Add input validation if needed
if number < 0:
raise ValueError("Encryption only supports non-negative integers")
# Rest of the implementation...
Which of the following problems can be solved with backtracking (select multiple)
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 assets algo monster recursion jpg You first call Ben and ask
Want a Structured Path to Master System Design Too? Don’t Miss This!