FastPrepSort by Odd-Position Digit Sum

Sort by Odd-Position Digit Sum

Pelatro logoPelatro● MediumFULLTIMEONSITE INTERVIEW

Problem statement

Given a string numbers of space-separated unsigned decimal tokens, return the tokens in ascending order of their odd-position digit sums.

For each token, number its digits from 1 starting at the left. Its key is the sum of digits at positions 1, 3, 5, .... For example, the key of 107 is 1 + 7 = 8.

Preserve the original order of tokens whose keys are equal. Preserve every token exactly, including leading zeros, and separate output tokens with one ASCII space.

Use scalar scans of the input string rather than collections or another array. Buffers used only to construct the returned string are permitted.

Function

sortByOddDigitSum(numbers: String) → String

Examples

Example 1

numbers = "56 65 107 11"return = 11 56 65 107

The keys of 56, 65, 107, and 11 are 5, 6, 8, and 1. Ascending keys give 11 56 65 107.

Example 2

numbers = "22 11 002 20"return = 11 22 002 20

The keys of 22, 11, 002, and 20 are 2, 1, 2, and 2. The key-2 tokens retain their original order, so the result is 11 22 002 20.

Constraints

  • 1 <= numbers.length <= 6199.
  • The string contains 1 to 200 tokens separated by exactly one ASCII space, with no leading or trailing spaces.
  • Each token contains 1 to 30 ASCII digits from 0 to 9. Leading zeros are allowed; signs and decimal points are absent.
  • Do not use collections or any array to store or reorder the tokens. Scalar variables, string indexing, and buffers used only to construct the returned string are allowed.

More Pelatro problems

See Pelatro hiring insights
Saved
public String sortByOddDigitSum(String numbers) {
    // Write your solution here.
}
numbers"56 65 107 11"
expected"11 56 65 107"
Checking account…