Rearrange Digits Under an Adjacent-Sum Limit
Updated
Problem statement
You are given a non-empty string digits made of decimal digits. Rearrange its characters, using each one exactly once. In the new order, every two digits that sit next to each other must add up to at most 9.
Return the lexicographically largest valid order. Every valid order has the same length, so this means: compare two orders from the left, and at the first place where they differ, the one with the bigger digit is larger. If no valid order exists, return the empty string.
Function
rearrangeDigits(digits: String) → StringExamples
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"Put the digits from largest to smallest. The neighboring sums are 7, 5, and 3, so this order is valid. No order of these digits can be larger than largest-to-smallest, so it is the answer.
Example 3
digits = "889"return = ""Any two of the three digits add up to more than 9, so no order can use all of them. The answer is the empty string.
Constraints
1 <= digits.length <= 100000digitscontains only characters'0'through'9'.- Leading zeroes are ordinary characters and must be preserved.
More Amazon Phone Screen questions
- Course SchedulePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Search in a Rotated Sorted ArrayPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Top K Frequent ElementsOA · PHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- LRU Cache for Query ResultsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Course Schedule IIPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Minimum Time to Spread Through a GridPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Consistent-Hash Packet RouterPHONE SCREEN · Seen Nov 2026
- Count Connected ComponentsPHONE SCREEN · Seen Nov 2026
- Second Largest Distinct ElementPHONE SCREEN · Seen Nov 2026
- Task SchedulerOA · PHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Largest Number Below N from Reusable DigitsByteDance · PHONE SCREENByteDance interview questions
- Remove K DigitsProcol · PHONE SCREEN
- Reorderable Task Scheduler With CooldownWaymo · PHONE SCREENWaymo interview questions
- Phone-Number Letter CombinationsHeadway · PHONE SCREENHeadway interview questions
- Letter Combinations of a Phone NumberLinkedIn · PHONE SCREENLinkedIn interview questions
- String Permutations in Custom Character OrderWex · OA · PHONE SCREEN
- Valid Parenthesis StringOracle · PHONE SCREENOracle interview questions
- Shortest Way to Form a Target StringPinterest · PHONE SCREENPinterest interview questions
- Numeric Poker OperationsRippling · PHONE SCREENRippling interview questions
- Maximize Workday EarningsCitadel · OA · PHONE SCREEN · ONSITE INTERVIEWCitadel interview questions