ProgrammingVery hardTCS NQT · Accenture
For the array a = [1, 2, 3, 5, 4] the next permutation (in lexicographic order) is computed by the standard procedure: find the last i with a[i] < a[i+1], swap a[i] with the smallest larger element to its right, then reverse the suffix after position i. What is the result printed as a string of digits?
For the array a = [1, 2, 3, 5, 4] the next permutation (in lexicographic order) is computed by the standard procedure: find the last i with a[i] < a[i+1], swap a[i] with the smallest larger element to its right, then reverse the suffix after position i. What is the result printed as a string of digits?
i = largest index with a[i] < a[i+1] j = largest index with a[j] > a[i] swap a[i], a[j]; reverse a[i+1..n-1] Print a
- A. 12345
- B. 12435
- C. 12453
- D. 45321
Correct answer: B. 12435
The last ascent is 3 < 5, so 3 is swapped with 4 (the smallest larger value to its right) giving 1 2 4 5 3, and the suffix 5 3 is reversed to 3 5, giving 1 2 4 3 5. Printing the sorted array, skipping the suffix reversal, and printing the reversed array each give different strings.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Array a = [3, 6, -2, -5, 7, 3]. The procedure below finds the largest product of two adjacent elements. What is printed? best = a[0] a[1]…
- The loop below prints the running count for i = 1, 4, 7, 10, ... up to and including 20 (i increases by 3 each time). What is the number…
- Array a = [1, 2, 1, 2, 3, 2, 1, 1] is processed left to right. The procedure below finds the length of the longest run of equal…
- Array a = [1, 1, 2, 2, 2, 3, 4, 4] is sorted. The two-pointer procedure below removes duplicates in place (keeping one copy of each value)…
- Array a = [4, 9, 1, 7, 3]. The procedure below finds the sum of all elements that are greater than the mean of the array. What is printed?…
- Array a = [2, 5, 7, 10, 12] is searched for the number of elements less than or equal to 7 by a binary search that finds the boundary…