Minimum Element After Replacement With Digit Sum - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [10,12,13,14]
Output: 1
💡 Note: Replace elements: 10→1, 12→3, 13→4, 14→5. Array becomes [1,3,4,5]. Minimum is 1.
Example 2 — Larger Numbers
$ Input: nums = [1,2,3,4]
Output: 1
💡 Note: Single digit numbers remain unchanged: [1,2,3,4]. Minimum is 1.
Example 3 — Multi-digit Numbers
$ Input: nums = [999,191,22]
Output: 4
💡 Note: Replace elements: 999→27 (9+9+9), 191→11 (1+9+1), 22→4 (2+2). Array becomes [27,11,4]. Minimum is 4.

Constraints

  • 1 ≤ nums.length ≤ 100
  • 1 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Minimum Element After Digit Sum Replacement INPUT nums = [10, 12, 13, 14] 10 idx 0 12 idx 1 13 idx 2 14 idx 3 Digit Sum Calculation: 10 --> 1+0 = 1 12 --> 1+2 = 3 13 --> 1+3 = 4 14 --> 1+4 = 5 After Replacement: 1 3 4 5 ALGORITHM STEPS 1 Initialize min Set minVal = infinity 2 Iterate Array For each element in nums 3 Compute Digit Sum Sum all digits of num 4 Update Minimum minVal = min(minVal, sum) Single Pass Trace: num sum minVal 10 1 1 12 3 1 13 4 1 14 5 1 FINAL RESULT Minimum digit sum found: 1 OK - Answer: 1 From digit sums [1,3,4,5] the minimum is 1 Source: 10 (1+0=1) O(n * d) time Key Insight: Single pass optimization: Instead of storing all digit sums, we compute each sum on-the-fly and immediately compare with the running minimum. This achieves O(1) space complexity while maintaining O(n * d) time where d is the average number of digits per element. TutorialsPoint - Minimum Element After Replacement With Digit Sum | Single Pass Approach
Asked in
Meta 12 Google 8
12.0K Views
Medium Frequency
~10 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen