#3300

Minimum Element After Replacement With Digit Sum

Easy
ArrayMathHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of converting each number to a string, we can directly compute the digit sum using arithmetic operations. This is more efficient and avoids the overhead of string manipulation.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a variable to hold the minimum value.
  2. 2Step 2: For each number in the array, compute the digit sum using a loop.
  3. 3Step 3: Compare the computed sum with the current minimum and update if necessary.
  4. 4Step 4: Return the minimum value after processing all numbers.
solution.py17 lines
1# Full working Python code
2
3def digit_sum(n):
4    sum = 0
5    while n > 0:
6        sum += n % 10
7        n //= 10
8    return sum
9
10def min_element_after_replacement(nums):
11    min_value = float('inf')
12    for num in nums:
13        min_value = min(min_value, digit_sum(num))
14    return min_value
15
16# Example usage
17print(min_element_after_replacement([10, 12, 13, 14]))  # Output: 1

Complexity note: The time complexity is O(n) because we only loop through the array once, and for each number, we compute the digit sum in O(log m) time. However, since log m is a constant factor for our input constraints, we can consider it O(n).

  • 1Directly summing digits using arithmetic is more efficient than string manipulation.
  • 2The minimum digit sum can be found in a single pass through the array.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.