Suppose you are given an array and a procedure reverse which reverses the order of elements in between positions and (both inclusive). What does the following sequence do, where :
reverse (s, 1, k);
reverse (s, k+1, n);
reverse (s, 1, n);View worked solution
Answer: A
To understand the effect of the given sequence of operations, let us represent the array as the concatenation of two subarrays, and :
- of length
- of length
Thus, the initial array is .
Let denote the reversal of a sequence . Let's trace the operations step-by-step:
-
reverse(s, 1, k): Reverses the first elements (subarray ).
The array becomes: -
reverse(s, k+1, n): Reverses the remaining elements (subarray ).
The array becomes: -
reverse(s, 1, n): Reverses the entire array.
The reversal of the concatenated sequence is: The array becomes:
Since the initial array has been transformed into , the first elements have moved to the end, and the remaining elements have shifted to the front. This is precisely a left rotation of by positions.
Example:
Let with and .
- After
reverse(s, 1, 2): - After
reverse(s, 3, 5): - After
reverse(s, 1, 5):
This is a left rotation of the original array by positions, confirming that Option A is correct.
Free practice · Your answers on this page are not saved.
