VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-sum-two-numbers-formed-digits-array/

⇱ Minimum Sum of Two Numbers Formed from Digits of an Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum Sum of Two Numbers Formed from Digits of an Array

Last Updated : 20 Apr, 2026

Given an array arr[] of digits (values are from 0 to 9), find the minimum possible sum of two numbers formed using all digits of the array.

Note: We need to return the minimum possible sum as a string.

Examples:

Input: arr[] = [6, 8, 4, 5, 2, 3, 0]
Output: "604"
Explanation: The minimum sum is formed by numbers 0358 and 246.

Input: arr[] = [5, 3, 0, 7, 4]
Output: "82"
Explanation: The minimum sum is formed by numbers 35 and 047.

[Naive Approach] Using Sorting - O(n log n) time and O(n) space

A minimum number will be formed from set of digits when smallest digit appears at most significant position and next smallest digit appears at next most significant position and so on. The idea is to first sort the digits in increasing order so that smaller digits come first. Then, we form two numbers by alternately picking digits from the sorted array. This ensures that the smallest digits are placed at the most significant positions of both numbers, keeping them balanced in length and minimizing their sum.

Illustration:


Output
604

[Expected Approach] Using Count Array - O(n) time and O(n) space

This approach uses a count array to store the frequency of digits from 0 to 9, avoiding the need for sorting. By traversing the count array from smallest to largest digit and alternately assigning digits to two numbers while avoiding leading zeros, we can efficiently construct the two numbers with minimum sum in linear time.

Algorithm:

  • Create a count array to store frequency of digits (0–9).
  • Traverse digits from 0 to 9 and alternately add digits that are present to s1 and s2.
  • Skip leading zeros while forming numbers.
  • Add both numbers using string addition and return result.

Output
604
Comment
Article Tags: