Maximize number with one digit swap
MetaSoftware Engineer · OnsiteLast updated
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.
Given a non-negative integer n (as an int or string), perform at most one swap of two digits to produce the maximum possible value. Return the resulting integer. Design an O(L) algorithm (L = number of digits) using last-occurrence tracking of digits and scan from most significant to least significant. Include an early exit when the current digit is already the largest available to its right and no better swap exists.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.