The sphinx's digits
- O(n²) · Very hard
- Full plan
- Python
- JavaScript
- digits
- strings
- indexes
Problem
Where the road crosses the dunes, a stone sphinx carves a number into the rock and grants the traveler a single move: swap two digits, once, or leave the number as it is. Only those who leave the largest possible number may pass.
Write a function that takes number, a string of digits (at least one, no leading zeros), and returns, as a string, the largest number you can get with at most one swap of two digits.
With "2736", swapping the 2 and the 7 gives "7236", and no other swap gives more, so you return "7236". With "1993" there are two nines: swapping the 1 with the first one gives "9193", but with the last one it gives "9913", which is larger.
If no swap makes it bigger, as with "9973" or "5", return the same string you received.
Examples
The example
"2736" → "7236"
Already the largest
"9973" → "9973"
Swapped with the last nine
"1993" → "9913"
A single digit
"5" → "5"
Two digits in the wrong order
"12" → "21"
The largest is at the end
"876129" → "976128"
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def biggest_swap(number):
passJavaScript
function biggestSwap(number) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.