JPMORGAN Coding Question β Solved
Perform a series of operations on a given array of integers. Each operation consists of two indices that define a subarray to reverse, inclusive of those indices.
Return the resulting array after all operations have been applied in the specified order.
Example
arr = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
operations = [[0, 9], [4, 5], [3, 6], [2, 7], [1, 8], [0, 9]]
In the first operation, all elements are reversed. There are no elements to the right or left.
In the second operation, only the elements in the subarray defined by indices 4 to 5 are reversed. Those to the left and right remain unchanged.
Similar logic is applied for further operations.
Function Description
Complete the function performOperations in the editor with the following parameters:
int arr[n]: an array of integers
int operations[q][2]: a 2-dimensional array of starting and ending indices
Returns
int[n]: the final array after all operations have been performed
Constraints
Β· 1 β€ n, q β€ 10^3
Β· 0 β€ arr[i] β€ 10^3
Β· 0 β€ operations[i][0] β€ operations[i][1] < n
Sample Case 0
Input
arr = [1, 2, 3]
operations = [[0, 2], [1, 2], [0, 2]]
Output
[2, 1, 3]
Explanation
Step 1: Reverse arr[0:2] β [3, 2, 1]
Step 2: Reverse arr[1:2] β [3, 1, 2]
Step 3: Reverse arr[0:2] β [2, 1, 3]
Asked in:
JPMORGAN