DDSA Solutions

3300. Minimum Element After Replacement With Digit Sum

Time: O(n * d)
Space: O(1)
Advertisement

Intuition

Each element is independently replaced by the sum of its digits, then we need the minimum among transformed values. Since replacement does not depend on other elements, a single pass with a running minimum is optimal.

Algorithm

  1. 1Initialise ans = +infinity.
  2. 2For each number num in nums:
  3. 3 Compute digitSum(num) by repeatedly taking num % 10 and num /= 10.
  4. 4 Update ans = min(ans, digitSum(num)).
  5. 5Return ans after processing all elements.

Example Walkthrough

Input: nums = [10, 12, 13, 14]

  1. 1.digitSum(10) = 1, ans = 1.
  2. 2.digitSum(12) = 3, ans stays 1.
  3. 3.digitSum(13) = 4, digitSum(14) = 5, ans stays 1.

Output: 1

Common Pitfalls

  • Remember that digit sum for 0 is 0; guard if inputs can include 0.
  • Do not sort just to find a minimum transformed value; one pass is enough.
  • Digit-sum computation should use integer operations, not string conversion, for efficiency and simplicity.
3300.cs
C#
// Approach: Replace each number by its digit sum and track the minimum digit sum seen.
// Compute digit sums in O(number of digits) per element and update a running minimum.
// Time: O(n * d) Space: O(1), where d is average digit count.

public class Solution
{
    public int MinElement(int[] nums)
    {
        int ans = int.MaxValue;
        foreach (int num in nums)
            ans = Math.Min(ans, GetDigitSum(num));
        return ans;
    }

    private int GetDigitSum(int num)
    {
        int digitSum = 0;
        while (num > 0)
        {
            digitSum += num % 10;
            num /= 10;
        }
        return digitSum;
    }
}
Advertisement
Was this solution helpful?