Minimum Element After Replacement With Digit Sum Problem
#3300
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3300.
You are given an integer array nums.
You replace each element in nums with the sum of its digits.
Return the minimum element in nums after all replacements.
Example 1:
Input: nums = [10,12,13,14]
Output: 1
Explanation:
nums becomes [1, 3, 4, 5] after all replacements, with minimum element 1.
Example 2:
Input: nums = [1,2,3,4]
Output: 1
Explanation:
nums becomes [1, 2, 3, 4] after all replacements, with minimum element 1.
Example 3:
Input: nums = [999,19,199]
Output: 10
Explanation:
nums becomes [27, 10, 19] after all replacements, with minimum element 10.
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 10^4
Solution
Approach: Simulation
Compute the digit sum of every element and keep the smallest one.
Complexity: O(n log M) time and O(1) space, where n is the length of nums and M its largest value.
class Solution:
def minElement(self, nums: List[int]) -> int:
return min(sum(int(b) for b in str(x)) for x in nums)