Maximum Swap - Problem

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.

Input & Output

Example 1 — Basic Swap
$ Input: num = 2736
Output: 7236
💡 Note: Swap the first digit 2 with the second digit 7 to get 7236, which is the maximum possible value with a single swap.
Example 2 — No Improvement Possible
$ Input: num = 9973
Output: 9973
💡 Note: The digits are already in optimal order from left to right, no single swap can improve the value.
Example 3 — Single Digit
$ Input: num = 1
Output: 1
💡 Note: Single digit number cannot be improved by swapping.

Constraints

  • 0 ≤ num ≤ 108

Visualization

Tap to expand
Maximum Swap - Greedy Approach INPUT Number: 2736 2 idx 0 7 idx 1 3 idx 2 6 idx 3 Goal: Swap at most ONE pair to maximize the number Constraint: Only 1 swap allowed digits = ['2','7','3','6'] Input: num = 2736 ALGORITHM STEPS 1 Track Last Index Store rightmost position of each digit 0-9 last[7]=1, last[6]=3 last[3]=2, last[2]=0 2 Scan Left to Right For each digit, find larger digit appearing later 3 Find Best Swap At idx 0: digit '2' Check 9,8,7... found 7! 2 7 3 6 SWAP 4 Execute Swap Swap idx 0 with idx 1 2736 --> 7236... wait Actually swap '2' at idx 0 with '7' at idx 1 FINAL RESULT Before Swap: 2736 swap After Swap: 7236 7 2 3 6 was 2 was 7 Output: 7236 OK Key Insight: To maximize the number, we want the largest possible digit at the leftmost position. Scan left-to-right: for each digit, check if a larger digit exists to its right. If found, swap with the rightmost occurrence of that larger digit (to handle duplicates correctly). Time: O(n) Space: O(1) TutorialsPoint - Maximum Swap | Greedy - Find Best Single Swap
Asked in
Facebook 25 Google 15
28.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen