Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Rearrange the digits of a version list into the next lexicographically greater permutation.
Problem: Rearrange the digits of a version list into the next lexicographically greater permutation.
def nxt(a):
i = len(a) - 2
while i >= 0 and a[i] >= a[i+1]: i -= 1
if i >= 0:
j = len(a) - 1
while a[j] <= a[i]: j -= 1
a[i], a[j] = a[j], a[i]
a[i+1:] = reversed(a[i+1:])
return a
print(nxt([1, 3, 5, 4, 2]))What is printed?- A. [1, 4, 5, 3, 2]
- B. [1, 4, 2, 5, 3]
- C. [1, 4, 2, 3, 5]
- D. [1, 3, 5, 2, 4]
Correct answer: C. [1, 4, 2, 3, 5]
The rightmost ascent is at 3 (index 1). Swap it with the smallest larger value to its right, 4, giving [1,4,5,3,2], then reverse the suffix to make it smallest: [1,4,2,3,5]. Forgetting the reverse leaves [1,4,5,3,2].
More Coding Interview Problems questions
- An analytics service holds a static array of n = 10⁵ integers and must answer q = 10⁶ queries 'minimum of a[l..r]' as fast as possible…
- Given n = 5 × 10⁴ integers, count pairs i < j with a[i] > 2·a[j]. Which approach is correct and efficient?
- Problem: Evaluate a reverse-Polish expression. The specification says division must truncate toward zero (as in C or Java). python def…
- Problem: Sum the minimum of every contiguous subarray using a monotonic stack (previous-less and next-less-or-equal boundaries). python…
- Problem: Count the distinct non-empty substrings of a short string. python s = "ababa" print(len({s[i:j] for i in range(len(s)) for j in…
- Problem: Compute the KMP prefix function (pi[i] = length of the longest proper prefix of s[0..i] that is also its suffix). python def…