KatInterview

Find Optimal Single Digit Exchange to Maximize Value

StringsModel answer
MediumModel answerStringsgreedystring-manipulationoptimization

Last updated

Swap at most two digits in a non-negative integer to achieve the largest possible result.

You are given a non-negative integer represented either as an int or as a string of digits. Your task is to find the maximum value you can obtain by swapping at most one pair of digits.

Return the resulting integer after performing the optimal swap, or the original number if no beneficial swap exists.

Examples:

  • Input: 2736 → Output: 7236 (exchange the first and second digits)
  • Input: 9973 → Output: 9973 (no swap improves the value)
  • Input: 1993 → Output: 9913 (swap the first digit with the rightmost 9)
  • Input: 98368 → Output: 98863 (exchange digits at positions 2 and 4)

Constraints:

  • The input is a valid non-negative integer
  • You may perform zero or one swap
  • Design a solution that runs in O(L) time, where L is the number of digits

What to provide:

  1. Your algorithm and approach
  2. Implementation in a language of your choice
  3. Time and space complexity analysis
  4. How you handle edge cases

Hints

Hint 1

Think about which position contributes most to the number's magnitude—where should you focus your search?

Hint 2

For a given position, if multiple candidates could be swapped in, which occurrence of that digit gives the best result?

Hint 3

Consider precomputing useful metadata about digit positions in a single pass before making your decision.