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 3
Explanation:
Operations performed on the array arr1[] as follows:
Step 1: Append 1 into the array and reverse it. arr1[] = {1}
Step 2: Append 2 into the array and reverse it. arr1[] = {2, 1}
Step 3: Append 3 into the array and reverse it. arr1[] = {3, 1, 2}
Step 3: Append 4 into the array and reverse it. arr1[] = {4, 2, 1, 3}Input: arr[] Â = {1, 2, 3}
Output: 3 1 2
Explanation:
Operations performed on the array arr1[] as follows:
Step 1: Append 1 into the array and reverse it. arr1[] = {1}
Step 2: Append 2 into the array and reverse it. arr1[] = {2, 1}
Step 3: Append 3 into the array and reverse it. arr1[] = {3, 1, 2}
Naive Approach: The simplest approach to solve the problem is to iterate over the array arr[] and insert each element of arr[] one by one into the array arr1[] and reverse the array arr1[] after each insertion.Â
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to use the Doubly Ended Queue (Deque) to append the elements at both ends. Follow the steps below to solve the problem:
- Initialize a Double Ended Queue for storing the elements of the converted array.
- Iterate over the elements of the array arr[] and push the elements to the front of the Deque if the index of the element and length of the element have the same parity. Otherwise, at the push it to the back of the Deque.
- Finally, after the complete iteration of the array arr[], print the contents of the Deque as the required arrangement of output.
Below is the implementation of the above approach:
C++
// C++ program of the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to generate the array by// inserting array elements one by one// followed by reversing the arrayvoid generateArray(int arr[], int n){Â
    // Doubly ended Queue    deque<int> ans;Â
    // Iterate over the array    for (int i = 0; i < n; i++) {Â
        // Push array elements        // alternately to the front        // and back        if (i & 1)            ans.push_front(arr[i]);        else            ans.push_back(arr[i]);    }Â
    // If size of list is odd    if (n & 1) {Â
        // Reverse the list        reverse(ans.begin(),                ans.end());    }Â
    // Print the elements    // of the array    for (auto x : ans) {        cout << x << " ";    }    cout << endl;}Â
// Driver Codeint32_t main(){Â Â Â Â int n = 4;Â Â Â Â int arr[n] = { 1, 2, 3, 4 };Â Â Â Â generateArray(arr, n);Â Â Â Â return 0;} |
Java
// Java program of the above approach import java.io.*;import java.util.*;Â
class GFG{     // Function to generate the array by// inserting array elements one by one// followed by reversing the arraystatic void generateArray(int arr[], int n){         // Doubly ended Queue    Deque<Integer> ans = new LinkedList<>();      // Iterate over the array    for(int i = 0; i < n; i++)     {                 // Push array elements        // alternately to the front        // and back        if ((i & 1) != 0)            ans.addFirst(arr[i]);        else            ans.add(arr[i]);    }      // If size of list is odd    if ((n & 1) != 0)     {                 // Reverse the list        Collections.reverse(Arrays.asList(ans));     }      // Print the elements    // of the array    for(int x : ans)    {        System.out.print(x + " ");    }    System.out.println();}  // Driver Codepublic static void main (String[] args){    int n = 4;    int arr[] = { 1, 2, 3, 4 };         generateArray(arr, n);}}Â
// This code is contributed by code_hunt |
Python3
# Python3 program of the above approach from collections import dequeÂ
# Function to generate the array by# inserting array elements one by one# followed by reversing the arraydef generateArray(arr, n):      # Doubly ended Queue    ans = deque()      # Iterate over the array    for i in range(n):          # Push array elements        # alternately to the front        # and back        if (i & 1 != 0):            ans.appendleft(arr[i])        else:            ans.append(arr[i])         # If size of list is odd    if (n & 1 != 0):          # Reverse the list        ans.reverse()         # Print the elements    # of the array    for x in ans:        print(x, end = " ")         print()Â
# Driver Coden = 4arr = [ 1, 2, 3, 4 ]Â
generateArray(arr, n)Â
# This code is contributed by code_hunt |
C#
// C# program of // the above approach using System;using System.Collections.Generic;class GFG{     // Function to generate the array // by inserting array elements // one by one followed by // reversing the arraystatic void generateArray(int []arr,                           int n){     // Doubly ended Queue  List<int> ans = new List<int>();Â
  // Iterate over the array  for(int i = 0; i < n; i++)   {    // Push array elements    // alternately to the front    // and back    if ((i & 1) != 0)      ans.Insert(0, arr[i]);    else      ans.Add(arr[i]);  }Â
  // If size of list is odd  if ((n & 1) != 0)   {    // Reverse the list    ans.Reverse();   }Â
  // Print the elements  // of the array  foreach(int x in ans)  {    Console.Write(x + " ");  }  Console.WriteLine();}  // Driver Codepublic static void Main(String[] args){  int n = 4;  int []arr = {1, 2, 3, 4};  generateArray(arr, n);}}Â
// This code is contributed by 29AjayKumar |
Javascript
<script>Â
// Javascript program of the above approachÂ
// Function to generate the array by// inserting array elements one by one// followed by reversing the arrayfunction generateArray(arr, n){Â
    // Doubly ended Queue    var ans = [];Â
    // Iterate over the array    for (var i = 0; i < n; i++) {Â
        // Push array elements        // alternately to the front        // and back        if (i & 1)            ans.splice(0,0,arr[i]);        else            ans.push(arr[i]);    }Â
    // If size of list is odd    if (n & 1) {Â
        // Reverse the list        ans.reverse();    }Â
    // Print the elements    // of the array    ans.forEach(x => {Â
        document.write( x + " ");    });}Â
// Driver Codevar n = 4;var arr =Â [1, 2, 3, 4];generateArray(arr, n);Â
</script> |
4 2 1 3
Â
Time Complexity: O(N)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



