FastPrepSwap Parity (Data Scientist / Analytics :)

Swap Parity (Data Scientist / Analytics :)

JP Morgan Chase logoJP Morgan Chase● MediumINTERNOA
Learn

Problem statement

Given a number num, two adjacent digits can be swapped if they have the same parity, meaning both are odd or both are even. For example, (5, 9) have the same parity, but (6, 9) do not.

Find the largest number that can be created. The swap operation can be applied any number of times.

Function

getLargestNumber(num: String) → String

Examples

Example 1

num = "7596801"return = "9758601"

Let num = "7596801".

  • Swap 5 and 9 -> "7956801"
  • Swap 7 and 9 -> "9756801"
  • Swap 6 and 8 -> "9758601"

The largest value possible is "9758601".

Example 2

num = "0082663"return = "8662003"

The prefix 008266 is one contiguous run of even digits, so it can be reordered into descending order as 866200. The final odd digit 3 cannot cross that even run. Therefore, the largest reachable number is 8662003.

Constraints

  • 1 ≤ length of num ≤ 10^5
  • num consists of digits 0-9 only.

More JP Morgan Chase problems

See JP Morgan Chase hiring insights
public String getLargestNumber(String num) {
  // write your code here
}
num"7596801"
expected"9758601"
Checking account…