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?- A. 8415 9193 98863 7654
- B. 8514 9193 98863 7654
- C. 8415 9913 98836 7654
- 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
- Problem: Flower i blooms on day bloom[i]. A bouquet needs k ADJACENT bloomed flowers, each flower used once. Find the minimum day by which…
- Problem: A number is 'magical' if it is divisible by a or b. Find the n-th magical number by binary search with inclusion–exclusion…
- Problem: Find the maximum difference between successive values in the SORTED order of an array, in linear time, using buckets (pigeonhole…
- Problem: Camera clips (start, end) cover parts of an event lasting T = 10 minutes; clips may be trimmed. Find the minimum number of clips…
- Problem: A broken calculator shows start and supports only 'double' and 'decrement by 1'. Find the minimum operations to reach target…
- Problem: Return the largest number ≤ n whose digits are non-decreasing from left to right. python def mono(n): d = list(str(n)); mark =…