Solved Problem - Reverse Subarray
In this lesson, we'll discuss a solved problem about how to reverse the given subarray of an array.
We'll cover the following
Problem statement
Given an array of integers. Answer queries of the type - reverse the subarray . Print the array after each query.
Input format The first line contains two integers and .
The second line contains space-separated integers representing the array .
Next, lines each contains pair of integers and .
Sample
Input
5 3
1 2 3 4 5
1 5
2 3
3 5
Output
5 4 3 2 1
5 3 4 2 1
5 3 1 2 4
Solution
For each query, we can reverse the given array in time. Let’s see how we would reverse the entire array; we can then do the same to reverse a subarray.
We start with two pointers, one at the start and one at the end of the array. Pointer 1 moves to the right and Pointer 2 moves to the left after each step. At each step, we swap the elements at the two pointers.
See the below illustrations for better understanding.
Get hands-on with 1400+ tech skills courses.