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 the index of the array elements after performing given operations K times
Next article icon

Find the final sequence of the array after performing given operations

Last Updated : 04 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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, 
 

  1. Append arr[i] to the end of b[].
  2. 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 
 

Operation b[]
1 {1}
2 {2, 1}
3 {3, 1, 2}
4 {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}. 
 

Operation b[]
1 {4}
2 {8, 4}
3 {6, 4, 8}
4 {1, 8, 4, 6}
5 {7, 6, 4, 8, 1}
6 {9, 1, 8, 4, 6, 7}

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++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function that generates the
// array b[] when n is even
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 odd
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 type
void 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 code
int main()
{
    int arr[] = { 1, 2, 3, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    solve(n, arr);
 
    return 0;
}
 
 

Java




// Java implementation of the approach
import java.io.*;
 
class GFG
{
 
// Function that generates the
// array b[] when n is even
static 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 odd
static 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 type
static 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 code
public 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..
 
 

Python3




# Python 3 implementation of the approach
 
# Function that generates the
# array b[] when n is even
def 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 odd
def 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 type
def 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 code
if __name__ == '__main__':
    arr = [1, 2, 3, 4]
    n = len(arr)
 
    solve(n, arr)
 
# This code is contributed by
# Surendra_Gangwar
 
 

C#




// C# implementation of the approach
using System;
 
class GFG
{
 
// Function that generates the
// array b[] when n is even
static 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 odd
static 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 type
static 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 code
public static void Main ()
{
    int []arr = { 1, 2, 3, 4 };
    int n = arr.Length;
     
    solve(n, arr);
}
}
 
// This code is contributed by anuj_67..
 
 

Javascript




<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>
 
 
Output: 
4 2 1 3

 

Time Complexity: O(n)

Auxiliary Space: O(n)

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++




// 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 code
int 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




// Java implementation of the approach
import 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#




// C# implementation of the approach
using 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




# Python3 implementation of the approach
def 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 Code
arr = [1, 2, 3, 4]
n = len(arr)
 
b = solve(arr, n)
 
print(b)
 
# This code is contributed by Mohit kumar
 
 

Javascript




<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>
 
 
Output: 
[4, 2, 1, 3]

 

Time Complexity: O(n)

Auxiliary Space: O(1)



Next Article
Find the index of the array elements after performing given operations K times

A

ajourney
Improve
Article Tags :
  • Arrays
  • DSA
  • Mathematical
Practice Tags :
  • Arrays
  • Mathematical

Similar Reads

  • Find the modified array after performing k operations of given type
    Given an array arr[] of n integers and an integer K. In one operation every element of the array is replaced by the difference of that element and the maximum value of the array. The task is to print the array after performing K operations.Examples: Input: arr[] = {4, 8, 12, 16}, k = 2 Output: 0 4 8
    10 min read
  • Find the index of the array elements after performing given operations K times
    Given an array arr[] and an integer K, the task is to print the position of the array elements, where the ith value in the result is the index of the ith element in the original array after applying following operations exactly K times: Remove the first array element and decrement it by 1.If it is g
    7 min read
  • Find the final number obtained after performing the given operation
    Given an array of positive distinct integers arr[], the task is to find the final number obtained by performing the following operation on the elements of the array: Operation: Take two unequal numbers and replace the larger number with their difference until all numbers become equal.Examples: Input
    7 min read
  • Find the increased sum of the Array after P operations
    Given an array arr[] of non-negative integers of size N and an integer P. Neighboring values of every non-zero element are incremented by 2 in each operation, the task is to find the increased sum of the array after P operations. Examples: Input: arr[] = {0, 5, 0, 4, 0}, P = 2Output: 24Explanation:
    12 min read
  • Reduce all array elements to zero by performing given operations thrice
    Given an array arr[] of size N, the task is to convert every array element to 0 by applying the following operations exactly three times: Select a subarray.Increment every element of the subarray by the integer multiple of its length. Finally, print the first and last indices of the subarray involve
    9 min read
  • Minimum element left from the array after performing given operations
    Given an array arr[] of N integers, the task is to remove the elements from both the ends of the array i.e. in a single operation, either the first or the last element can be removed from the current remaining elements of the array. This operation needs to be performed in such a way that the last el
    3 min read
  • Find the resulting output array after doing given operations
    Given an array integers[] of integers of size N. Find the resulting output array after doing some operations: If the (i-1)th element is positive and ith element is negative then :If the absolute of (i)th is greater than (i-t)th, remove all the contiguous positive elements from left having absolute v
    11 min read
  • Find the size of the final imaginary Array after removing the balls
    Given 2 arrays color[]and radius[] of length N each representing N balls, where color[i] represents the color of the ith ball while radius[i] represents the radius of the ith ball. If two consecutive balls have the same color and size, both are removed from the array, the task is to find the length
    12 min read
  • Maximum sum of all elements of array after performing given operations
    Given an array of integers. The task is to find the maximum sum of all the elements of the array after performing the given two operations once each. The operations are: 1. Select some(possibly none) continuous elements from the beginning of the array and multiply by -1. 2. Select some(possibly none
    7 min read
  • Maximum Possible Product in Array after performing given Operations
    Given an array with size N. You are allowed to perform two types of operations on the given array as described below: Choose some position i and j, such that (i is not equals to j), replace the value of a[j] with a[i]*a[j] and remove the number from the ith cell.Choose some position i and remove the
    13 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