Problem · String

Best Way to Pack

Learn this problem
HardAmazonFULLTIMEOA
See Amazon hiring insights

Problem statement

The team at an Amazon warehouse is given a task to optimize the packing of a set of boxes with different IDs. Each box is labeled with an ID, and these boxes are currently arranged in a single row from left to right, where the ID of the i-th box is represented by the string s_id consisting of digits from 0 to 9 inclusive.

To make the packing more efficient, the team can perform the following operation any (possibly zero) number of times:

  • Choose an index i and remove the digit s_id[i]. Then insert the box with ID min(s_id[i] + 1, 9) on any position (at the beginning, at the end, or in between any two adjacent boxes) in the row.

Given a string s_id, find the lexicographically minimal string of boxes using these operations.

Note: A string X is lexicographically smaller than a string Y of the same length if and only if, in the first position where X and Y differ, the string X has a smaller digit than the corresponding digit in Y.

Function

bestWayToPack(id: String) → String

Examples

Example 1

id = "26547"return = "24677"
Starting from "26547": delete 5 and insert 6 (min(5+1,9)) to get "26467"; then delete the 6 at the 2nd position and insert 7 (min(6+1,9)) in the 4th position to get "24677". It can be proved that "24677" is the lexicographically minimal string possible.

Example 2

id = "34892"return = "24677"
Starting from "26547": delete 5 and insert 6 (min(5+1,9)) to get "26467"; then delete the 6 at the 2nd position and insert 7 (min(6+1,9)) in the 4th position to get "24677". It can be proved that "24677" is the lexicographically minimal string possible.

Constraints

Constraints:

  • s_id consists only of digits from 0 to 9 inclusive.
  • Each operation removes exactly one digit and inserts exactly one digit, so the length of the string is preserved.
  • The inserted digit for a removed digit d is min(d + 1, 9).

More Amazon problems

drafts saved locally
public String bestWayToPack(String id) {
  // write your code here
}
id"26547"
expected"24677"
checking account