Find element at given index after given range reversals

An array consisting of N elements is given. There are several reversals we do in unique ranges[L..R]. The task is to print the element at given index.
Examples:Â
Input :
arr[] : 10 20 30 40 50
ranges[] = {{1, 4}, {0, 2}}
Query Index = 1
Output : 50
Explanation :
Reverse range[1..4] : 10 50 40 30 20
Reverse range[0..2] : 40 50 10 30 20
So we have 50 at index 1
The Brute Force approach would be to actually reverse a range of elements and answer the queries afterward.
Efficient Method: If we observe, the reversal of range[L..R] will result as follows :Â
The index will become right + left – index.Â
By doing this, we can compute the index easily.Â
Implementation:
C++
// Program to find index of an element after// given range reversals.#include <bits/stdc++.h>using namespace std;Â
// Function to compute the element at query indexint answer(int arr[], int ranges[][2], int reversals,           int index){    for (int i = reversals - 1; i >= 0; i--) {        // Range[left...right]        int left = ranges[i][0], right = ranges[i][1];Â
        // If doesn't satisfy, reversal won't        // have any effect        if (left <= index && right >= index)            index = right + left - index;    }Â
    // Returning element at modified index    return arr[index];}Â
// Driverint main(){Â Â Â Â int arr[] = { 10, 20, 30, 40, 50 };Â
    // reversals    int reversals = 2;    int ranges[reversals][2] = { { 1, 4 }, { 0, 2 } };Â
    int index = 1;    cout << answer(arr, ranges, reversals, index);Â
    return 0;} |
Java
// Program to find index of an element// after given range reversals.import java.util.Arrays;Â
class GFG {    // Function to compute the element at    // query index    static int answer(int[] arr, int[][] ranges,                      int reversals, int index)    {        for (int i = reversals - 1; i >= 0; i--) {            // Range[left...right]            int left = ranges[i][0],                right = ranges[i][1];Â
            // If doesn't satisfy, reversal            // won't have any effect            if (left <= index && right >= index)                index = right + left - index;        }Â
        // Returning element at modified index        return arr[index];    }Â
    // Driver code    public static void main(String[] args)    {Â
        int[] arr = { 10, 20, 30, 40, 50 };Â
        // reversals        int reversals = 2;        int[][] ranges = { { 1, 4 }, { 0, 2 } };Â
        int index = 1;        System.out.println(answer(arr, ranges,                                  reversals, index));    }}Â
/* This code is contributed by Mr. Somesh Awasthi */ |
Python3
# Program to find index of an element # after given range reversals.Â
# Function to compute the element# at query indexdef answer(arr, ranges, reversals, index):Â Â Â Â i = reversals - 1Â Â Â Â while(i >= 0):Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â # Range[left...right]Â Â Â Â Â Â Â Â left = ranges[i][0]Â Â Â Â Â Â Â Â right = ranges[i][1]Â
        # If doesn't satisfy, reversal won't        # have any effect        if (left <= index and right >= index):            index = right + left - index             i -= 1         # Returning element at modified index    return arr[index]Â
# Driver Codeif __name__ == '__main__':Â Â Â Â arr = [10, 20, 30, 40, 50]Â
    # reversals    reversals = 2    ranges = [ [ 1, 4 ], [ 0, 2 ] ]Â
    index = 1    print(answer(arr, ranges,                 reversals, index))Â
# This code is contributed by # Surendra_Gangwar |
C#
// C# program to find index of an element// after given range reversals.using System;Â
class GFG {         // Function to compute the element at    // query index    static int answer(int[] arr, int[, ] ranges,                       int reversals, int index)    {        for (int i = reversals - 1; i >= 0; i--)        {                         // Range[left...right]            int left = ranges[i, 0],                right = ranges[i, 1];Â
            // If doesn't satisfy, reversal            // won't have any effect            if (left <= index && right >= index)                index = right + left - index;        }Â
        // Returning element at modified index        return arr[index];    }Â
    // Driver code    public static void Main()    {Â
        int[] arr = { 10, 20, 30, 40, 50 };Â
        // reversals        int reversals = 2;        int[, ] ranges = { { 1, 4 }, { 0, 2 } };Â
        int index = 1;        Console.WriteLine(answer(arr, ranges,                                reversals, index));    }}Â
// This code is contributed by vt_m. |
Javascript
<script>Â
    // Program to find index of an element    // after given range reversals.         // Function to compute the element at    // query index    function answer(arr, ranges, reversals, index)    {        for (let i = reversals - 1; i >= 0; i--) {            // Range[left...right]            let left = ranges[i][0],                right = ranges[i][1];               // If doesn't satisfy, reversal            // won't have any effect            if (left <= index && right >= index)                index = right + left - index;        }           // Returning element at modified index        return arr[index];    }         let arr = [ 10, 20, 30, 40, 50 ];       // reversals    let reversals = 2;    let ranges = [ [ 1, 4 ], [ 0, 2 ] ];Â
    let index = 1;    document.write(answer(arr, ranges, reversals, index));         </script> |
PHP
<?php// Program to find index // of an element after// given range reversals.Â
// Function to compute the// element at query indexfunction answer($arr, $ranges, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â $reversals, $index){Â Â Â Â for ($i = $reversals - 1; Â Â Â Â Â Â Â Â Â Â Â Â Â Â $i >= 0; $i--) Â Â Â Â {Â Â Â Â Â Â Â Â // Range[left...right]Â Â Â Â Â Â Â Â $left = $ranges[$i][0]; Â Â Â Â Â Â Â Â $right = $ranges[$i][1];Â
        // If doesn't satisfy,        // reversal won't have         // any effect        if ($left <= $index &&             $right >= $index)            $index = $right + $left -                               $index;    }Â
    // Returning element    // at modified index    return $arr[$index];}Â
// Driver Code$arr = array( 10, 20, 30, 40, 50 );Â
// reversals$reversals = 2;$ranges = array(array( 1, 4 ), Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â array( 0, 2 ));Â
$index = 1;echo answer($arr, $ranges,            $reversals, $index);Â
// This code is contributed // by nitin mittal.?> |
50
Optimized solution
We can start by applying all the reversals to the array in the order they are given. To do this efficiently, we can use a helper function to reverse a given range of elements in the array. After applying all the reversals, we can answer the queries directly by accessing the element at the given index.
Algorithm
First define function reverseRange(arr, L, R) that takes an array arr such that
a.Two indices L and R as input.
If L < R, THAN swap the elements at indices L and R in the array arr.
After that Increment L and decrement R.
Define a function applyReversals(arr, ranges)
For each pair of indices (L, R) in ranges, call the reverseRange function with arguments (arr, L, R).
Define a function getElementAtIndex(arr, index)
Return the element of arr at index index.
Initialize an array arr and a list of ranges ranges.
Call the applyReversals and getElementAtIndex function
Assign the result to variable result.
Get result as output.
Implementation of above program
C++
#include <iostream>#include <vector>using namespace std;Â
void reverseRange(vector<int>& arr, int L, int R) {Â Â Â Â while (L < R) {Â Â Â Â Â Â Â Â swap(arr[L], arr[R]);Â Â Â Â Â Â Â Â L++;Â Â Â Â Â Â Â Â R--;Â Â Â Â }}Â
void applyReversals(vector<int>& arr, vector<pair<int, int>>& ranges) {Â Â Â Â for (int i = 0; i < ranges.size(); i++) {Â Â Â Â Â Â Â Â int L = ranges[i].first;Â Â Â Â Â Â Â Â int R = ranges[i].second;Â Â Â Â Â Â Â Â reverseRange(arr, L, R);Â Â Â Â }}Â
int getElementAtIndex(vector<int>& arr, int index) {Â Â Â Â return arr[index];}Â
int main() {    // initialize inputs    vector<int> arr = {10, 20, 30, 40, 50};    vector<pair<int, int>> ranges = {{1, 4}, {0, 2}};    int queryIndex = 1;Â
    // apply reversals and answer query    applyReversals(arr, ranges);    int result = getElementAtIndex(arr, queryIndex);Â
    // output result    cout << result << endl;Â
    return 0;} |
Java
import java.util.ArrayList;import java.util.List;Â
public class ArrayReversalQuery {    // Function to reverse a range of elements in the array    public static void reverseRange(List<Integer> arr,                                    int L, int R)    {        while (L < R) {            int temp = arr.get(L);            arr.set(L, arr.get(R));            arr.set(R, temp);            L++;            R--;        }    }Â
    // Function to apply a list of reversal ranges to the    // array    public static void applyReversals(List<Integer> arr,                                      List<int[]> ranges)    {        for (int i = 0; i < ranges.size(); i++) {            int L = ranges.get(i)[0];            int R = ranges.get(i)[1];            reverseRange(arr, L, R);        }    }Â
    // Function to get an element at a specific index in the    // array    public static int getElementAtIndex(List<Integer> arr,                                        int index)    {        return arr.get(index);    }Â
    public static void main(String[] args)    {        // Initialize inputs        List<Integer> arr = new ArrayList<>();        arr.add(10);        arr.add(20);        arr.add(30);        arr.add(40);        arr.add(50);Â
        List<int[]> ranges = new ArrayList<>();        ranges.add(new int[] { 1, 4 }); // Reversal range 1        ranges.add(new int[] { 0, 2 }); // Reversal range 2Â
        int queryIndex = 1; // Index for the queryÂ
        // Apply reversals to the array        applyReversals(arr, ranges);Â
        // Get the element at the specified query index        int result = getElementAtIndex(arr, queryIndex);Â
        // Output the result        System.out.println(result);    }} |
Python
def reverseRange(arr, L, R):Â Â Â Â while L < R:Â Â Â Â Â Â Â Â arr[L], arr[R] = arr[R], arr[L]Â Â Â Â Â Â Â Â L += 1Â Â Â Â Â Â Â Â R -= 1Â
def applyReversals(arr, ranges):Â Â Â Â for L, R in ranges:Â Â Â Â Â Â Â Â reverseRange(arr, L, R)Â
def getElementAtIndex(arr, index):Â Â Â Â return arr[index]Â
# initialize inputsarr = [10, 20, 30, 40, 50]ranges = [(1, 4), (0, 2)]queryIndex = 1Â
# apply reversals and answer queryapplyReversals(arr, ranges)result = getElementAtIndex(arr, queryIndex)Â
# output resultprint(result) |
C#
using System;using System.Collections.Generic;Â
class Program {Â Â Â Â static void ReverseRange(List<int> arr, int L, int R)Â Â Â Â {Â Â Â Â Â Â Â Â while (L < R) {Â Â Â Â Â Â Â Â Â Â Â Â // Swap elements at indices L and RÂ Â Â Â Â Â Â Â Â Â Â Â int temp = arr[L];Â Â Â Â Â Â Â Â Â Â Â Â arr[L] = arr[R];Â Â Â Â Â Â Â Â Â Â Â Â arr[R] = temp;Â Â Â Â Â Â Â Â Â Â Â Â L++;Â Â Â Â Â Â Â Â Â Â Â Â R--;Â Â Â Â Â Â Â Â }Â Â Â Â }Â
    static void    ApplyReversals(List<int> arr,                   List<Tuple<int, int> > ranges)    {        foreach(var range in ranges)        {            int L = range.Item1;            int R = range.Item2;            ReverseRange(arr, L, R);        }    }Â
    static int GetElementAtIndex(List<int> arr, int index)    {        return arr[index];    }Â
    static void Main()    {        // Initialize inputs        List<int> arr = new List<int>{ 10, 20, 30, 40, 50 };        List<Tuple<int, int> > ranges            = new List<Tuple<int, int> >{                  Tuple.Create(1, 4), Tuple.Create(0, 2)              };        int queryIndex = 1;Â
        // Apply reversals and answer query        ApplyReversals(arr, ranges);        int result = GetElementAtIndex(arr, queryIndex);Â
        // Output result        Console.WriteLine(result);    }} |
Javascript
// Function to reverse a range [L, R] in an arrayfunction reverseRange(arr, L, R) {Â Â Â Â while (L < R) {Â Â Â Â Â Â Â Â // Swap elements at indices L and RÂ Â Â Â Â Â Â Â [arr[L], arr[R]] = [arr[R], arr[L]];Â Â Â Â Â Â Â Â L++;Â Â Â Â Â Â Â Â R--;Â Â Â Â }}Â
// Function to apply a list of reversals to the given arrayfunction applyReversals(arr, ranges) {Â Â Â Â for (const range of ranges) {Â Â Â Â Â Â Â Â const L = range[0];Â Â Â Â Â Â Â Â const R = range[1];Â Â Â Â Â Â Â Â reverseRange(arr, L, R);Â Â Â Â }}Â
// Function to get an element at a specific index in the arrayfunction getElementAtIndex(arr, index) {Â Â Â Â return arr[index];}Â
// Main functionfunction main() {    // Initialize inputs    const arr = [10, 20, 30, 40, 50];    const ranges = [[1, 4], [0, 2]];    const queryIndex = 1;Â
    // Apply reversals and answer the query    applyReversals(arr, ranges);    const result = getElementAtIndex(arr, queryIndex);Â
    // Output the result    console.log(result);}Â
// Call the main function to execute the programmain(); |
50
 Time complexity  O(N*M), where N is the length of the input array arr and M is the number of ranges in the input ranges.Â
 Space complexity is O(1),as it does not use any additional memory.Â
This article is contributed by Rohit Thapliyal. If you like zambiatek and would like to contribute, you can also write an article using write.zambiatek.com or mail your article to review-team@zambiatek.com. See your article appearing on the zambiatek main page and help other Geeks.Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



