Given an array arr[] of size N, the task is to minimize the sum by removing all the occurrences of a single digit.
Examples:
Input: arr[] = {34, 23, 85, 93}
Output: 100
Explanation: Removing the occurrences of the digit 3 from each element of the array modifies arr[] to {4, 2, 85, 9}. Therefore, minimized sum of the array = 4 + 2 + 85 + 9 = 100.Input: arr[] = {434, 863, 342, 121}
Output: 293
Approach: The idea is to remove all occurrences of each possible digit ( [0, 9] ) one by one and calculate the sum of the array after removal of each of them. Finally, find the minimum of these sums. Follow the steps below to solve the problem:
- Initialize a variable, say minSum, to store the minimum sum and curSum to store the sum obtained after removing all occurrences of a digit.
- Iterate over the digits in the range [0, 9] and perform the following:
- Traverse the array arr[] and check for the minimum sum by removing every digit.
- After removing the digits from the string, convert the string back to an integer and add it to curSum.
- Update the value of minSum after each iteration.
- Print the value of minSum as the required answer.
Below is the implementation of the above approach:
Python3
# Python3 program for the above approach # Function to remove each digit # from the given integer def remove(N, digit): # Convert into string strN = str(N) # Stores final string ans = '' # Traverse the string for i in strN: if int(i) == digit: continue # Append it to the # final string ans += i # Return integer value return int(ans) # Function to find the minimum sum by # removing occurences of each digit def getMin(arr): minSum = float('inf') # Iterate in range [0, 9] for i in range(10): curSum = 0 # Traverse the array for num in arr: curSum += remove(num, i) # Update the minimum sum minSum = min(minSum, curSum) # Print the minimized sum print(minSum) # Given array arr = [34, 23, 85, 93] getMin(arr) |
100
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

