1 minute read

You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2, and all the digits found in num must be used.

For example, given num = 2932, you have the following digits: two 2’s, one 9 and one 3. Some of the possible pairs [new1, new2] are [22, 93], [23, 92], [223, 9] and [2, 329]. Return the minimum possible sum of new1 and new2.

Example 1:

Input: num = 2932 Output: 52 Explanation: Some possible pairs [new1, new2] are [29, 23], [223, 9], etc. The minimum sum can be obtained by the pair [29, 23]: 29 + 23 = 52. Example 2:

Input: num = 4009 Output: 13 Explanation: Some possible pairs [new1, new2] are [0, 49], [490, 0], etc. The minimum sum can be obtained by the pair [4, 9]: 4 + 9 = 13.

Constraints:

1000 <= num <= 9999

/**
 * @param {number} num
 * @return {number}
 */
var minSumAfterSplit = function (num) {
  // Convert the number to a string, split it into an array of characters, and sort the array
  num = num.toString().split("").sort();

  // Create the first new number (new1) by concatenating the first and third elements of the sorted array
  new1 = num[0] + num[2];

  // Create the second new number (new2) by concatenating the second and fourth elements of the sorted array
  new2 = num[1] + num[3];

  // Return the sum of the two new numbers as a numeric value
  return Number(new1) + Number(new2);
};

Converts the number to a string, splits it into an array of characters, and then sorts the array in ascending order.

Forms the first new number (new1) by concatenating the first and third elements of the sorted array.

Forms the second new number (new2) by concatenating the second and fourth elements of the sorted array.

Returns the sum of the two new numbers as a numeric value.

The time complexity is O(n log n) where n is the length of the array produced from splitting the string representation of the number.

Leave a comment