My first instinct was the naive approach, try every pair of digits, which is obviously not O(L).
First, clarify that the input is a non-negative integer and we can swap at most one pair of digits. Then, devise a linear-time algorithm by scanning from the right to track the maximum digit seen so far and the best swap candidate, ensuring we pick the leftmost digit that can be swapped with a larger digit to its right to maximize the number.
Pro tip: Mention that leading zeros are not a concern because swapping to increase the number will never introduce a leading zero unless the number is zero, and emphasize that the algorithm must handle the case where no swap improves the number (e.g., digits are non-increasing).
Confirm that the input is a non-negative integer, we can perform at most one swap, and we want the largest possible value. Discuss edge cases: single-digit number, all digits same, digits in non-increasing order (e.g., 54321), and numbers with zeros.
Convert the integer to a string or array of digits to allow easy manipulation and indexing. This also helps in discussing time complexity relative to the number of digits.
Scan from right to left, keeping track of the maximum digit seen so far and its index. For each digit, if it is less than the maximum digit seen, record it as a potential swap candidate (the leftmost such digit will yield the largest increase).
If a swap candidate is found, swap it with the rightmost occurrence of the maximum digit to its right. If no candidate, return the original number. Convert the digit array back to an integer.
State that the algorithm runs in O(n) time and O(n) space (or O(1) extra space if using string manipulation). Walk through a few examples to verify correctness, such as 2736 -> 7236, 9973 -> 9973, 98368 -> 98863.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.