FastPrepRearrange Digits Under an Adjacent-Sum Limit

Rearrange Digits Under an Adjacent-Sum Limit

Amazon logoAmazon● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

You are given a non-empty string digits containing decimal digits. Rearrange every character exactly once so that the numeric values of every two adjacent digits have sum at most 9.

Return the lexicographically largest valid rearrangement. If no valid rearrangement exists, return the empty string.

Function

rearrangeDigits(digits: String) → String

Examples

Example 1

digits = "188"return = "818"

The only valid arrangement places 1 between the two 8s. Its adjacent sums are both 9.

Example 2

digits = "1234"return = "4321"

The descending arrangement is valid because its adjacent sums are 7, 5, and 3, and no valid result can be lexicographically larger.

Example 3

digits = "889"return = ""

Every pair among the three available digits has sum greater than 9, so no arrangement can use all of them.

Constraints

  • 1 <= digits.length <= 100000
  • digits contains only characters '0' through '9'.
  • Leading zeroes are ordinary characters and must be preserved.

More Amazon problems

See Amazon hiring insights
public String rearrangeDigits(String digits) {
    // Write your code here.
}
digits"188"
expected"818"
Checking account…