Find the final sequence of the array after performing given operations - GeeksforGeeks

28 May, 2021
Given an array arr[] of size N, the task is to perform the following operation exactly N times, Create an empty list of integers b[] and in the ith operation,  
Append arr[i] to the end of b[].Reverse the elements in b[].
Append arr[i] to the end of b[].
Reverse the elements in b[].
Finally, print the contents of the list b[] after the end of all operations.Examples:  
Input: arr[] = {1, 2, 3, 4} Output: 4 2 1 3  
Input: arr[] = {1, 2, 3} Output: 3 1 2  
 
Approach: We need some observations to solve this problem. Suppose the number of elements in the array is even. Say our array is {4, 8, 6, 1, 7, 9}.  
After carefully observing, we conclude that for even size of elements in the array the numbers which are at even positions (index 1 based) are reversed and added at the beginning and the numbers which are at the odd positions are kept in same order and added in the end.While for odd-sized arrays, the elements at odd positions are reversed and added at the beginning while elements in the array at even positions are kept same and added in the end.Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that generates the// array b[] when n is evenvoid solveEven(int n, int* arr, int* b){    int left = n - 1;     // Fill the first half of the final array    // with reversed sequence    for (int i = 0; i < (n / 2); ++i) {        b[i] = arr[left];        left = left - 2;        if (left < 0)            break;    }     // Fill the second half    int right = 0;    for (int i = n / 2; i <= n - 1; ++i) {        b[i] = arr[right];        right = right + 2;        if (right > n - 2)            break;    }} // Function that generates the// array b[] when n is oddvoid solveOdd(int n, int* arr, int* b){     // Fill the first half of the final array    // with reversed sequence    int left = n - 1;    for (int i = 0; i < (n / 2) + 1; ++i) {        b[i] = arr[left];        left = left - 2;        if (left < 0)            break;    }     // Fill the second half    int right = 1;    for (int i = (n / 2) + 1; i <= n - 1; ++i) {        b[i] = arr[right];        right = right + 2;        if (right > n - 2)            break;    }} // Function to find the final array b[]// after n operations of given typevoid solve(int n, int* arr){     // Create the array b    int b[n];     // If the array size is even    if (n % 2 == 0)        solveEven(n, arr, b);    else        solveOdd(n, arr, b);     // Print the final array elements    for (int i = 0; i <= n - 1; ++i) {        cout << b[i] << " ";    }} // Driver codeint main(){    int arr[] = { 1, 2, 3, 4 };    int n = sizeof(arr) / sizeof(arr[0]);     solve(n, arr);     return 0;}
// Java implementation of the approachimport java.io.*; class GFG{ // Function that generates the// array b[] when n is evenstatic void solveEven(int n, int arr[], int b[]){    int left = n - 1;     // Fill the first half of the final array    // with reversed sequence    for (int i = 0; i < (n / 2); ++i)    {        b[i] = arr[left];        left = left - 2;        if (left < 0)            break;    }     // Fill the second half    int right = 0;    for (int i = n / 2; i <= n - 1; ++i)    {        b[i] = arr[right];        right = right + 2;        if (right > n - 2)            break;    }} // Function that generates the// array b[] when n is oddstatic void solveOdd(int n, int arr[], int b[]){     // Fill the first half of the final array    // with reversed sequence    int left = n - 1;    for (int i = 0; i < (n / 2) + 1; ++i)    {        b[i] = arr[left];        left = left - 2;        if (left < 0)            break;    }     // Fill the second half    int right = 1;    for (int i = (n / 2) + 1; i <= n - 1; ++i)    {        b[i] = arr[right];        right = right + 2;        if (right > n - 2)            break;    }} // Function to find the final array b[]// after n operations of given typestatic void solve(int n, int arr[]){     // Create the array b    int b[] = new int[n];     // If the array size is even    if (n % 2 == 0)        solveEven(n, arr, b);    else        solveOdd(n, arr, b);     // Print the final array elements    for (int i = 0; i <= n - 1; ++i)    {        System.out.print( b[i] + " ");    }} // Driver codepublic static void main (String[] args){    int []arr = { 1, 2, 3, 4 };    int n = arr.length;         solve(n, arr);}} // This code is contributed by anuj_67..
# Python 3 implementation of the approach # Function that generates the# array b[] when n is evendef solveEven(n, arr, b):    left = n - 1     # Fill the first half of the final array    # with reversed sequence    for i in range((n // 2)):        b[i] = arr[left]        left = left - 2        if (left < 0):            break     # Fill the second half    right = 0    for i in range(n // 2, n, 1):        b[i] = arr[right]        right = right + 2        if (right > n - 2):            break # Function that generates the# array b[] when n is odddef solveOdd(n, arr, b):         # Fill the first half of the final array    # with reversed sequence    left = n - 1    for i in range(n // 2 + 1):        b[i] = arr[left]        left = left - 2        if (left < 0):            break     # Fill the second half    right = 1    for i in range(n // 2 + 1, n, 1):        b[i] = arr[right]        right = right + 2        if (right > n - 2):            break # Function to find the final array b[]# after n operations of given typedef solve(n, arr):         # Create the array b    b = [0 for i in range(n)]     # If the array size is even    if (n % 2 == 0):        solveEven(n, arr, b)    else:        solveOdd(n, arr, b)     # Print the final array elements    for i in range(n):        print(b[i], end = " ") # Driver codeif __name__ == '__main__':    arr = [1, 2, 3, 4]    n = len(arr)     solve(n, arr) # This code is contributed by# Surendra_Gangwar
// C# implementation of the approachusing System; class GFG{ // Function that generates the// array b[] when n is evenstatic void solveEven(int n, int []arr,                             int []b){    int left = n - 1;     // Fill the first half of the final array    // with reversed sequence    for (int i = 0; i < (n / 2); ++i)    {        b[i] = arr[left];        left = left - 2;        if (left < 0)            break;    }     // Fill the second half    int right = 0;    for (int i = n / 2; i <= n - 1; ++i)    {        b[i] = arr[right];        right = right + 2;        if (right > n - 2)            break;    }} // Function that generates the// array b[] when n is oddstatic void solveOdd(int n, int []arr, int []b){     // Fill the first half of the final array    // with reversed sequence    int left = n - 1;    for (int i = 0; i < (n / 2) + 1; ++i)    {        b[i] = arr[left];        left = left - 2;        if (left < 0)            break;    }     // Fill the second half    int right = 1;    for (int i = (n / 2) + 1; i <= n - 1; ++i)    {        b[i] = arr[right];        right = right + 2;        if (right > n - 2)            break;    }} // Function to find the final array b[]// after n operations of given typestatic void solve(int n, int []arr){     // Create the array b    int []b = new int[n];     // If the array size is even    if (n % 2 == 0)        solveEven(n, arr, b);    else        solveOdd(n, arr, b);     // Print the final array elements    for (int i = 0; i <= n - 1; ++i)    {        Console.Write( b[i] + " ");    }} // Driver codepublic static void Main (){    int []arr = { 1, 2, 3, 4 };    int n = arr.Length;         solve(n, arr);}} // This code is contributed by anuj_67..
<script>    // Javascript implementation of the approach         // Function that generates the    // array b[] when n is even    function solveEven(n, arr, b)    {        let left = n - 1;         // Fill the first half of the final array        // with reversed sequence        for (let i = 0; i < parseInt(n / 2, 10); ++i)        {            b[i] = arr[left];            left = left - 2;            if (left < 0)                break;        }         // Fill the second half        let right = 0;        for (let i = parseInt(n / 2, 10); i <= n - 1; ++i)        {            b[i] = arr[right];            right = right + 2;            if (right > n - 2)                break;        }    }     // Function that generates the    // array b[] when n is odd    function solveOdd(n, arr, b)    {         // Fill the first half of the final array        // with reversed sequence        let left = n - 1;        for (let i = 0; i < parseInt(n / 2, 10) + 1; ++i)        {            b[i] = arr[left];            left = left - 2;            if (left < 0)                break;        }         // Fill the second half        let right = 1;        for (let i = parseInt(n / 2, 10) + 1; i <= n - 1; ++i)        {            b[i] = arr[right];            right = right + 2;            if (right > n - 2)                break;        }    }     // Function to find the final array b[]    // after n operations of given type    function solve(n, arr)    {         // Create the array b        let b = new Array(n);         // If the array size is even        if (n % 2 == 0)            solveEven(n, arr, b);        else            solveOdd(n, arr, b);         // Print the final array elements        for (let i = 0; i <= n - 1; ++i)        {            document.write( b[i] + " ");        }    }         let arr = [ 1, 2, 3, 4 ];    let n = arr.length;          solve(n, arr); </script>
4 2 1 3
 
Efficient Approach: The last Element of Array will be reversed only once. Last but one element will be reversed twice. Hence it goes to the last position in final result array ie b. Hence we can fill b array by iterating the original array from the end and placing elements at the not filled first index and not filled the last index. The same idea is implemented below. Below is the implementation of the above approach:  
C++
Java
C#
Python3
Javascript
// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; int* solve(int arr[], int n){    static int b[4];    int p = 0;    for (int i = n - 1; i >= 0; i--)    {        b[p] = arr[i--];        if (i >= 0)            b[n - 1 - p] = arr[i];        p++;    }    return b;} // Driver codeint main(){    int arr[] = { 1, 2, 3, 4 };    int n = sizeof(arr)/sizeof(arr[0]);         int *b ;    b = solve(arr, n);    for(int i = 0; i < n; i++)    cout << b[i] << " ";} // This code is contributed by Rajput-Ji
// Java implementation of the approachimport java.util.*;import java.lang.*;import java.io.*; class GFG {     static int[] solve(int[] arr, int n) {        int[] b = new int[n];        int p = 0;        for (int i = n - 1; i >= 0; i--) {            b[p] = arr[i--];            if (i >= 0)                b[n - 1 - p] = arr[i];            p++;        }        return b;    }     public static void main(String[] args)    {        int []arr = { 1, 2, 3, 4 };        int n = arr.length;                 int[] b = solve(arr, n);                 System.out.println(Arrays.toString(b));    }} // This code is contributed by Pramod Hosahalli
// C# implementation of the approachusing System;     class GFG{    static int[] solve(int[] arr, int n)    {        int[] b = new int[n];        int p = 0;        for (int i = n - 1; i >= 0; i--)        {            b[p] = arr[i--];            if (i >= 0)                b[n - 1 - p] = arr[i];            p++;        }        return b;    }     // Driver Code    public static void Main(String[] args)    {        int []arr = { 1, 2, 3, 4 };        int n = arr.Length;                 int[] b = solve(arr, n);                 Console.WriteLine("[" + String.Join(",", b) + "]");    }} // This code is contributed by Princi Singh
# Python3 implementation of the approachdef solve(arr, n):    b = [0 for i in range(n)]    p = 0    i = n - 1    while i >= 0:        b[p] = arr[i]        i -= 1        if (i >= 0):            b[n - 1 - p] = arr[i]        p += 1        i -= 1    return b # Driver Codearr = [1, 2, 3, 4]n = len(arr) b = solve(arr, n) print(b) # This code is contributed by Mohit kumar
<script>// javascript implementation of the approach    function solve(arr , n) {        var b = Array(n).fill(0);        var p = 0;        for (i = n - 1; i >= 0; i--) {            b[p] = arr[i--];            if (i >= 0)                b[n - 1 - p] = arr[i];            p++;        }        return b;    }              var arr = [ 1, 2, 3, 4 ];        var n = arr.length;         var b = solve(arr, n);         document.write("["+ b.toString()+ "]"); // This code contributed by aashish1995</script>
[4, 2, 1, 3]
 
vt_m
PramodHosahalli
SURENDRA_GANGWAR
princi singh
mohit kumar 29
Rajput-Ji
aashish1995
divyesh072019
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Program for Fibonacci numbers
C++ Data Types
Set in C++ Standard Template Library (STL)
Program to find GCD or HCF of two numbers
Coin Change | DP-7