Maximize number with one digit swap
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Onsite
Quick Answer: Maximize number with one digit swap evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- 0 <= n <= 10^9 (fits in a 32-bit int for the typed signatures).
- Leading zeros are not introduced into the integer return value (e.g. 120 -> 210, never 021).
- At most one swap of two digit positions is allowed.
- If no swap increases the value, the original number is returned unchanged.
Examples
Input: (2736,)
Expected Output: 7236
Explanation: Swap the leading 2 with the rightmost larger digit 7 to get 7236.
Input: (9973,)
Expected Output: 9973
Explanation: Already maximal; every digit is >= those to its right, so no swap improves it.
Input: (1993,)
Expected Output: 9913
Explanation: Swap the leading 1 with the rightmost 9 (the last occurrence) to get 9913.
Input: (98368,)
Expected Output: 98863
Explanation: Using the last occurrence of 8 (index 4) to swap with the 3 at index 2 yields 98863, beating swapping with an earlier 8.
Input: (0,)
Expected Output: 0
Explanation: Single digit; no swap possible.
Input: (11111,)
Expected Output: 11111
Explanation: All digits equal; any swap leaves the number unchanged.
Input: (120,)
Expected Output: 210
Explanation: Swap the leading 1 with the 2 to get 210; the trailing 0 is never moved into the leading position.
Input: ("1009",)
Expected Output: 9001
Explanation: String input; swap the leading 1 with the rightmost 9 to get 9001.
Hints
- Track the last (rightmost) index at which each digit 0-9 appears. Choosing the rightmost occurrence of a larger digit maximizes the gain when you swap it forward.
- Scan digits left to right (most significant first). The first position where a strictly larger digit exists somewhere to its right is where the optimal swap happens.
- For the current digit, search candidate digits from 9 down to current+1; take the first whose last occurrence is to the right, swap, and return immediately.
- Early exit: if a digit is already the largest available to its right, no swap there helps, so move on; once you make any swap you are done.