We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Bigger is Greater
Bigger is Greater
Sort by
recency
|
986 Discussions
|
Please Login in order to post a comment
Python solution
Java
My general algorithm for solving this is as follows: Let's use "dkhc" as the driving example.
Start looking from the right, and find the first pair of letters that is out of order. Here, 'd' and 'k' are out of order. Find the smallest letter to the right of the out-of-order letter that is greater than it. Here, 'h' is the smallest letter that is greater than 'd'. Swap those two letters. This gives us "hkdc". Bali real estate Finally, sort all the letters to the right of the original out-of-order index. Here, that means sorting "kdc" into "cdk". Altogether then, "hcdk" is the final answer.
Python3
Tip: A nice observation is that once we swap our pivot position and the character most to the right that is greater than our pivot, we can reverse the rest of the string after the pivot (instead of sort).
This is because while we were finding the character to swap, we already ensured that the elements to the right of the pivot ARE smaller jacqueline tortorice, so it's descending order. That's why reversing after the pivot point works.