DEV Community

Cover image for 3300. Minimum Element After Replacement With Digit Sum
MD ARIFUL HAQUE
MD ARIFUL HAQUE

Posted on

3300. Minimum Element After Replacement With Digit Sum

3300. Minimum Element After Replacement With Digit Sum

Difficulty: Easy

Topics: Mid Level, Array, Math, Biweekly Contest 140

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 <= 100
  • 1 <= nums[i] <= 10⁴

Hint:

  1. Convert to string and calculate the sum for each element.

Solution:

The solution replaces each element in the array with the sum of its digits, then returns the smallest resulting value. This is done without storing the transformed array, keeping memory usage low.

Approach:

  • Iterate through each number in the input array.
  • Compute the digit sum for the current number.
  • Track the minimum digit sum found so far.
  • Return the minimum value after processing all numbers.

Let's implement this solution in PHP: 3300. Minimum Element After Replacement With Digit Sum

<?php
/**
 * @param Integer[] $nums
 * @return Integer
 */
function minElement(array $nums): int
{
    ...
    ...
    ...
    /**
     * go to ./solution.php
     */
}

// Test cases
echo minElement([10,12,13,14]) . "\n";          // Output: 1
echo minElement([1,2,3,4]) . "\n";              // Output: 1
echo minElement([999,19,199]) . "\n";           // Output: 10
?>
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Digit sum calculation is performed using repeated modulus and integer division.
  • No auxiliary array is created — only the running minimum is stored.
  • Comparison and update happen in the same loop, making the solution efficient.

Complexity

  • Time Complexity: O(n * d) — where n is the array length and d is the number of digits in the largest number (max 5 digits since nums[i] ≤ 10⁴).
  • Space Complexity: O(1) — only a few integer variables are used.

Contact Links

If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!
Buy Me A Coffee

If you want more helpful content like this, feel free to follow me:

Top comments (0)