Data Structures & AlgorithmsHardProduct company OA

Problem: Swap at most two digits of a number once to obtain the maximum value. Record the last position of each digit and, scanning left to right, swap with the largest later digit.

Problem: Swap at most two digits of a number once to obtain the maximum value. Record the last position of each digit and, scanning left to right, swap with the largest later digit.
def max_swap(num):
    d = list(str(num)); last = {int(c): i for i, c in enumerate(d)}
    for i, c in enumerate(d):
        for big in range(9, int(c), -1):
            if last.get(big, -1) > i:
                j = last[big]; d[i], d[j] = d[j], d[i]
                return int("".join(d))
    return num
print(max_swap(4815), max_swap(1993), max_swap(98368), max_swap(7654))
What is printed?
  1. A. 8415 9193 98863 7654
  2. B. 8514 9193 98863 7654
  3. C. 8415 9913 98836 7654
  4. D. 8415 9913 98863 7654

Correct answer: D. 8415 9913 98863 7654

Improve the leftmost digit that has a larger digit after it, swapping with the LAST occurrence of the largest such digit (so the smaller digit moves as far right as possible). 1993: swap 1 with the last 9 → 9913, not 9193. 98368: 9 and 8 are already best; 3 swaps with the later 8 → 98863. 7654 is non-increasing → unchanged. O(10·d).

More Coding Interview Problems questions

Exams that ask this topic