AlgoInsight

DSA problem

Maximum Swap

MediumGreedyPattern: Greedytop600AmazonMicrosoftGoogleBloombergFacebook

You are given an integer num. You can swap two digits at most once to get the maximum valued number. Return the maximum valued number you can get.

A brute-force solution tries every pair of digit positions and keeps the best resulting number. With d digits this is O(d^2) swaps, each generating a number we compare to the running best — fine for the tiny input bound but unsatisfying because it ignores the obvious greedy structure of the problem.

The greedy insight is that a beneficial swap moves a large digit leftward into the position of a smaller digit. To maximize the result, we want the leftmost place where we can place a strictly larger digit. So for each position i from left to right, we ask: somewhere to the right of i, is there a digit strictly greater than s[i]? If yes, swap s[i] with the rightmost occurrence of the largest such digit (rightmost so that, among equal large digits, we keep low-value ones up front in the trailing portion).

To do this in a single pass, precompute maxRight[i] = index of the maximum digit in s[i..n - 1] (ties broken by latest index). Then sweep i left to right; the first index where s[maxRight[i + 1]] > s[i] is the swap target. One swap, return the result. This runs in O(d) time and O(d) space, both linear in the number of digits.

Examples

Example 1
Input: num = 2736
Output: 7236
Explanation: Swap the leading 2 with the 7 to make the leading digit as large as possible: the result 7236 is the largest value obtainable with a single swap.
Example 2
Input: num = 9973
Output: 9973
Explanation: The digits are already arranged so that no swap increases the value; the leading 9s are already maximal, so the original number is returned.
Example 3
Input: num = 98368
Output: 98863
Explanation: Swap the second 3 (digit at index 3) with the rightmost 8 (digit at index 4) to lift an 8 into a higher place value, producing 98863.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

greedymathstring

Browse all DSA problems