Data Structures & AlgorithmsHardProduct Company SDE · permutation round
Problem: Find the next lexicographic permutation of the digits '1243' (the smallest permutation strictly greater than it). Run the code.
Problem: Find the next lexicographic permutation of the digits '1243' (the smallest permutation strictly greater than it). Run the code.
def next_perm(s):
a = list(s)
i = len(a) - 2
while i >= 0 and a[i] >= a[i + 1]:
i -= 1
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 ''.join(a)
print(next_perm('1243'))What is printed?- A. 1342
- B. 1423
- C. 2134
- D. 1324
Correct answer: D. 1324
The pivot is 2 (index 1), it swaps with the smallest larger suffix digit 3 to give 1 3 4 2, and the suffix then sorts to 2 4, so the answer is 1324.
More Coding Interview Problems questions
- Problem: Find the length of the longest substring of 'AABABBA' that can be made all one letter after at most k = 1 replacement. Run the…
- Problem: How many bits must be flipped to convert A = 29 into B = 15? Run the code. python A, B = 29, 15 print(bin(A ^ B).count('1')) What…
- Problem: What is printed by the stack-based decoder for '3[a2[c]]'? It expands k[s] to s repeated k times. python def decode(s): stack =…
- Problem: What is the minimum number of swaps needed to sort the permutation [4, 3, 2, 1] (values 1..4 each once)? Use the cycle…
- Problem: What is floor(sqrt(2000)) found by binary search? Run the code. python lo, hi = 0, 2000 while lo < hi: mid = (lo + hi + 1) // 2…
- Problem: Tasks with (duration, deadline) are (3,5), (2,4), (4,9), (1,3). Scheduling by earliest deadline first, how many tasks finish on…