Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Find original Array from given Array where each element is sum of prefix and postfix sum
Next article icon

Find the original array from given array obtained after P prefix reversals

Last Updated : 05 Jul, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size N and an integer P (P < N), the task is to find the original array from the array obtained by P prefix reversals where in ith reversal the prefix of size i of the array containing indices in range [0, i-1] was reversed.

Examples:

Input: arr[] = {4, 2, 1, 3, 5, 6}, P = 4.
Output:  1 2 3 4 5 6
Explanation: {1, 2, 3, 4, 5, 6} on prefix reversal P = 1 converts to {1, 2, 3, 4, 5, 6}.
{1, 2, 3, 4, 5, 6} on prefix reversal P = 2 converts to {2, 1, 3, 4, 5, 6}.
{2, 1, 3, 4, 5, 6} on prefix reversal P = 3 converts to {3, 1, 2, 4, 5, 6}
{3, 1, 2, 4, 5, 6} on prefix reversal P = 4 converts to  {4, 2, 1, 3, 5, 6} 
So answer is {1, 2, 3, 4, 5, 6}

Input: arr[] = {10, 9, 8, 3, 5, 6}, P = 3
Output: 9 8 10 3 5 6 

 

Naive Approach: To solve the problem reverse the prefix of size i in each step for i in range [1, P] starting from the P sized prefix and then gradually decrementing the size.

Algorithm

  • Initialize a pointer “end” to N-1.
  • For i in range [P, 1] do the following steps:
    •  Initialize a pointer “start” to i-1.
    •  While “start” is less than or equal to “end”, swap the elements at indices “start” and “end” and increment “start” and decrement “end”.
  • Reverse the entire array.

Implementation of the above approach

C++




#include <iostream>
#include <algorithm>
#include <vector>
 
using namespace std;
 
vector<int> reverse_array(vector<int> arr, int n, int p) {
    for (int i = p; i > 0; i--) {
        reverse(arr.begin(), arr.begin() + i);
    }
    return arr;
}
 
int main() {
    vector<int> arr = {4, 2, 1, 3, 5, 6};
    int n = arr.size();
    int p = 4;
    vector<int> result = reverse_array(arr, n, p);
 
    for (int i = 0; i < n; i++) {
        cout << result[i] << " ";
    }
    cout << endl;
 
    return 0;
}
 
 

Java




import java.util.Arrays;
 
public class MyClass {
     
    public static int[] reverseArray(int[] arr, int n, int p) {
        for (int i = p; i > 0; i--) {
            int[] reversed = new int[i];
            for (int j = 0; j < i; j++) {
                reversed[j] = arr[j];
            }
            for (int j = 0; j < i / 2; j++) {
                int temp = reversed[j];
                reversed[j] = reversed[i - j - 1];
                reversed[i - j - 1] = temp;
            }
            for (int j = 0; j < i; j++) {
                arr[j] = reversed[j];
            }
        }
        return arr;
    }
 
    public static void main(String[] args) {
        int[] arr = {4, 2, 1, 3, 5, 6};
        int n = arr.length;
        int p = 4;
        int[] result = reverseArray(arr, n, p);
        System.out.println(Arrays.toString(result));
    }
}
 
 

Python




def reverse_array(arr, n, p):
    for i in range(p, 0, -1):
        arr[:i] = arr[:i][::-1]
    return arr
 
# Example usage
arr = [4, 2, 1, 3, 5, 6]
n = len(arr)
p = 4
result = reverse_array(arr, n, p)
print(result)
 
 

C#




// C# code for the above approach
using System;
using System.Collections.Generic;
 
public class MainClass
{
    static List<int> reverse_array(List<int> arr, int n, int p)
    {
        for (int i = p; i > 0; i--)
        {
            arr.Reverse(0, i);
        }
        return arr;
    }
 
    public static void Main(string[] args)
    {
        List<int> arr = new List<int> { 4, 2, 1, 3, 5, 6 };
        int n = arr.Count;
        int p = 4;
        List<int> result = reverse_array(arr, n, p);
 
        foreach (int num in result)
        {
            Console.Write(num + " ");
        }
        Console.WriteLine();
    }
}
 
// This code is contributed by Pushpesh Raj
 
 

Javascript




// Javascript code for the above approach
// Define a function that reverses subarrays of an array
function reverseArray(arr, n, p)
{
  for (let i = p; i > 0; i--)
  {
   
    // Reverse the subarray arr[0...i-1] using slice, reverse, and concat methods
    arr = arr.slice(0, i).reverse().concat(arr.slice(i));
  }
  return arr;
}
 
// Define the main function
function main() {
  const arr = [4, 2, 1, 3, 5, 6];
  const n = arr.length;
  const p = 4;
  const result = reverseArray(arr, n, p);
  console.log(result.join(" "));
}
 
// Call the main function
main();
 
 
Output
[1, 2, 3, 4, 5, 6]  

Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: This solution is based on two pointer approach. Since there is only P prefix reversals, the first P elements of the array only gets affected remaining remains the same. So a pattern can be observed for the original and the array after P prefix reversals. Only the first P elements should be modified. Follow these steps to solve the above problem:

  • Initialize two variables l = 0 and r = P-1 
  • Initialize a vector res to store the modified prefix and index = 0 to keep track of elements at odd and even indices.
  • Using a while loop iterate through the prefix of arr[].
    • If the index is even push arr[l] into the vector res and increment l.
    • Else push arr[r]  into the vector res and decrement r.
    • Increment the index also.
  • Now reverse the res and assign the modified prefix to the prefix of length p of arr.
  • Print the original array.

 Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
void find_original_array(int arr[], int n, int p)
{
    // Initialize the r and l
    int r = p - 1;
    int l = 0;
 
    // Initialize index = 0
    // to track elements at
    // odd and even positions
    int index = 0;
    vector<int> res;
 
    while (l <= r) {
 
        // If index is even
        if (index % 2 == 0) {
            res.push_back(arr[l++]);
        }
 
        // If index is odd
        else {
            res.push_back(arr[r--]);
        }
 
        // Increment index
        index = index + 1;
    }
 
    // Reverse the res
    reverse(res.begin(), res.end());
 
    // Assign the modified prefix to arr
    for (int i = 0; i < res.size(); i++) {
        arr[i] = res[i];
    }
 
    // Print the array arr
    // which is the original array
    // modified from the
    // prefix reversed array
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
}
 
// Driver code
int main()
{
 
    int arr[] = { 4, 2, 1, 3, 5, 6 }, P = 4;
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    find_original_array(arr, n, P);
 
    return 0;
}
 
 

Java




// Java program for the above approach
import java.util.*;
public class GFG
{
  static void find_original_array(int arr[], int n, int p)
  {
 
    // Initialize the r and l
    int r = p - 1;
    int l = 0;
 
    // Initialize index = 0
    // to track elements at
    // odd and even positions
    int index = 0;
    ArrayList<Integer> res = new ArrayList<Integer>();
 
    while (l <= r) {
 
      // If index is even
      if (index % 2 == 0) {
        res.add(arr[l++]);
      }
 
      // If index is odd
      else {
        res.add(arr[r--]);
      }
 
      // Increment index
      index = index + 1;
    }
 
    // Reverse the res
    Collections.reverse(res);
 
    // Assign the modified prefix to arr
    for (int i = 0; i < res.size(); i++) {
      arr[i] = (int)res.get(i);
    }
 
    // Print the array arr
    // which is the original array
    // modified from the
    // prefix reversed array
    for (int i = 0; i < n; i++) {
      System.out.print(arr[i] + " ");
    }
  }
 
  // Driver code
  public static void main(String args[])
  {
 
    int arr[] = { 4, 2, 1, 3, 5, 6 }, P = 4;
    int n = arr.length;
 
    // Function call
    find_original_array(arr, n, P);
 
  }
}
 
// This code is contributed by Samim Hossain Mondal.
 
 

Python3




# Python program for the above approach
def find_original_array(arr, n, p):
 
    # Initialize the r and l
    r = p - 1;
    l = 0;
 
    # Initialize index = 0
    # to track elements at
    # odd and even positions
    index = 0;
    res = []
 
    while (l <= r):
 
        # If index is even
        if (index % 2 == 0):
            res.append(arr[l]);
            l += 1;
         
        # If index is odd
        else:
            res.append(arr[r]);
            r -= 1;
         
        # Increment index
        index = index + 1;
     
    # Reverse the res
    res.reverse();
 
    # Assign the modified prefix to arr
    for i in range(len(res)):
        arr[i] =  res[i];
     
    # Print array arr
    # which is the original array
    # modified from the
    # prefix reversed array
    for i in range(n):
        print(arr[i], end=" ");
     
# Driver code
if __name__ == '__main__':
 
    arr = [ 4, 2, 1, 3, 5, 6 ]
    P = 4;
    n = len(arr);
 
    # Function call
    find_original_array(arr, n, P);
 
# This code is contributed by gauravrajput1
 
 

C#




// C# program for the above approach
using System;
using System.Collections;
 
class GFG
{
  static void find_original_array(int []arr, int n, int p)
  {
 
    // Initialize the r and l
    int r = p - 1;
    int l = 0;
 
    // Initialize index = 0
    // to track elements at
    // odd and even positions
    int index = 0;
    ArrayList res = new ArrayList();
 
    while (l <= r) {
 
      // If index is even
      if (index % 2 == 0) {
        res.Add(arr[l++]);
      }
 
      // If index is odd
      else {
        res.Add(arr[r--]);
      }
 
      // Increment index
      index = index + 1;
    }
 
    // Reverse the res
    res.Reverse();
 
    // Assign the modified prefix to arr
    for (int i = 0; i < res.Count; i++) {
      arr[i] = (int)res[i];
    }
 
    // Print the array arr
    // which is the original array
    // modified from the
    // prefix reversed array
    for (int i = 0; i < n; i++) {
      Console.Write(arr[i] + " ");
    }
  }
 
  // Driver code
  public static void Main()
  {
 
    int []arr = { 4, 2, 1, 3, 5, 6 };
    int P = 4;
    int n = arr.Length;
 
    // Function call
    find_original_array(arr, n, P);
 
  }
}
 
// This code is contributed by Samim Hossain Mondal.
 
 

Javascript




<script>
    // JavaScript program for the above approach
 
    const find_original_array = (arr, n, p) => {
     
        // Initialize the r and l
        let r = p - 1;
        let l = 0;
 
        // Initialize index = 0
        // to track elements at
        // odd and even positions
        let index = 0;
        let res = [];
 
        while (l <= r) {
 
            // If index is even
            if (index % 2 == 0) {
                res.push(arr[l++]);
            }
 
            // If index is odd
            else {
                res.push(arr[r--]);
            }
 
            // Increment index
            index = index + 1;
        }
 
        // Reverse the res
        res.reverse();
 
        // Assign the modified prefix to arr
        for (let i = 0; i < res.length; i++) {
            arr[i] = res[i];
        }
 
        // Print the array arr
        // which is the original array
        // modified from the
        // prefix reversed array
        for (let i = 0; i < n; i++) {
            document.write(`${arr[i]} `);
        }
    }
 
    // Driver code
    let arr = [4, 2, 1, 3, 5, 6], P = 4;
    let n = arr.length;
 
    // Function call
    find_original_array(arr, n, P);
 
// This code is contributed by rakeshsahni
 
</script>
 
 
Output
1 2 3 4 5 6   

Time Complexity: O(N) where N is the length of the array.
Auxiliary Space: O(P) as the maximum size of res can be equal to P only. In a condition, when P=N, auxiliary space can reach to O(N)

 



Next Article
Find original Array from given Array where each element is sum of prefix and postfix sum

L

lokeshpotta20
Improve
Article Tags :
  • Algo Geek
  • Arrays
  • DSA
  • Greedy
  • Algo-Geek 2021
  • prefix
  • Reverse
  • two-pointer-algorithm
Practice Tags :
  • Arrays
  • Greedy
  • Reverse
  • two-pointer-algorithm

Similar Reads

  • Find original array from given array which is obtained after P prefix reversals | Set-2
    Given an array arr[] of size N and an integer P, the task is to find the original array from the array obtained by P prefix reversals where in ith reversal the prefix of size i of the array containing indices in range [0, i-1] was reversed. Note: P is less than or equal to N Examples: Input: arr[] =
    7 min read
  • Restore the original array from another array generated by given operations
    Given an array b. The array b is obtained initially by array a, by doing the following operations. Choose a fixed point x from array a.Cyclically rotate the array a to the left exactly x times.Fixed point x is that point where (a[i] = i ). These operations are performed on the array a k times, deter
    8 min read
  • Find original Array from given Array where each element is sum of prefix and postfix sum
    Given an array arr[] of length N, where arr is derived from an array nums[] which is lost. Array arr[] is derived as: arr[i] = (nums[0] + nums[1] + ... + nums[i]) + (nums[i] + nums[i+1] + ... + nums[N-1]). The task is to find nums[] array of length N. Examples: Input: N = 4, arr[] = {9, 10, 11, 10}O
    10 min read
  • Find the Prefix-MEX Array for given Array
    Given an array A[] of N elements, the task is to create a Prefix-MEX array for this given array. Prefix-MEX array B[] of an array A[] is created such that MEX of A[0] till A[i] is B[i]. MEX of an array refers to the smallest missing non-negative integer of the array. Examples: Input: A[] = {1, 0, 2,
    13 min read
  • Print the Array formed by reversing the given Array after each index
    Given an array arr[], the task is to print the array formed by traversing given array from first to the last index by flipping the whole array after printing every element. Example: Input: arr = {0, 1, 2, 3, 4, 5} Output: 0 4 2 2 4 0Explanation: On 1st iteration element on index 0 -> 0 is printed
    6 min read
  • Find Array formed by reversing Prefix each time given character is found
    Given an array arr[] of length N consisting of uppercase English letters only and a letter ch. the task is to find the final array that will form by reversing the prefix each time the letter ch is found in the array. Examples: Input: arr[] = {'A', 'B', 'X', 'C', 'D', 'X', 'F'}, ch= 'X'Output: D C X
    6 min read
  • Original Array from given Prefix Sums
    You are given a prefix sum array presum[] of an array arr[]. The task is to find the original array arr[] whose prefix sum is presum[]. Examples: Input: presum[] = {5, 7, 10, 11, 18}Output: [5, 2, 3, 1, 7]Explanation: Original array {5, 2, 3, 1, 7} Prefix sum array = {5, 5+2, 5+2+3, 5+2+3+1, 5+2+3+1
    4 min read
  • Maximum prefix sum after K reversals of a given array
    Given an array arr[] of size N and a positive integer K, the task is to find the maximum prefix sum after K reversals of the given array. Examples: Input: arr[] = {1, 5, 8, 9, 11, 2}, K = 1Output: 36Explanation: Reverse the array once. Therefore, the array becomes {2, 11, 9, 8, 5, 1}. Maximum prefix
    9 min read
  • Array obtained by repeatedly reversing array after every insertion from given array
    Given an array arr[], the task is to print the array obtained by inserting elements of arr[] one by one into an initially empty array, say arr1[], and reversing the array arr1[] after every insertion. Examples: Input: arr[] = {1, 2, 3, 4}Output: 4 2 1 3Explanation:Operations performed on the array a
    6 min read
  • Find original Array from the transformed Array
    Given two arrays arr1[] of length N and arr2[] of length N - 1 and is built such that arr2[i] = max(arr1[i], arr1[i+1]) for all 1 ≤ i ≤ N-1. The task is to find the original array arr1 of length N. Multiple answers may exist. Examples: Input: N = 5, arr2 = {3, 4, 4, 5}Output: {3, 3, 4, 4, 5}Explanat
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences