Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find the next lexicographic permutation of a digit list in place.
Problem: Find the next lexicographic permutation of a digit list in place.
def next_perm(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(next_perm([1, 3, 5, 4, 2]), next_perm([3, 2, 1]), next_perm([1, 1, 5]))What is printed?- A. [1, 4, 5, 3, 2] [1, 2, 3] [1, 5, 1]
- B. [1, 3, 5, 2, 4] [3, 2, 1] [1, 5, 1]
- C. [1, 4, 2, 3, 5] [3, 2, 1] [5, 1, 1]
- D. [1, 4, 2, 3, 5] [1, 2, 3] [1, 5, 1]
Correct answer: D. [1, 4, 2, 3, 5] [1, 2, 3] [1, 5, 1]
Find the rightmost i with a[i] < a[i + 1] (3 at index 1), swap it with the smallest larger value to its right (4), then reverse the suffix to make it ascending: [1, 4, 2, 3, 5]. A fully descending list wraps to the smallest. Forgetting the reverse gives [1, 4, 5, 3, 2]. O(n).
More Coding Interview Problems questions
- Problem: Count pairs of songs whose total duration is divisible by 60. python def pairs60(t): cnt = [0] 60; res = 0 for x in t: r = x % 60…
- Problem: Find the length of the longest subarray with equal numbers of 0s and 1s. python def longesteq(a): first = {0: -1}; bal = best = 0…
- Problem: Find all elements that appear more than ⌊n/3⌋ times. python def overthird(a): c1 = c2 = None; n1 = n2 = 0 for x in a: if x == c1…
- Problem: Find the length of the shortest unsorted continuous subarray which, if sorted, makes the whole array sorted. python def…
- Problem: Compute the amount of rain water trapped between bars. python def trap(h): l, r = 0, len(h) - 1; lm = rm = water = 0 while l < r…
- Problem: Find the three numbers in an array whose sum is closest to a target. python def closest3(a, t): a.sort(); best = a[0] + a[1] +…