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 Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Array obtained by repeatedly reversing array after every insertion from given array
Next article icon

Print the Array formed by reversing the given Array after each index

Last Updated : 30 Nov, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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 0
Explanation: On 1st iteration element on index 0 -> 0 is printed then the whole array is flipped:  {0, 1, 2, 3, 4, 5} -> {5, 4, 3, 2, 1, 0} 
                      On 2nd iteration element on index 1 -> 4 is printed then the whole array is flipped: : {5, 4, 3, 2, 1, 0} -> {0, 1, 2, 3, 4, 5} 
                      On 3rd iteration element on index 2 -> 2 is printed then the whole array is flipped:  {0, 1, 2, 3, 4, 5} -> {5, 4, 3, 2, 1, 0} 
                      On 2nd iteration element on index 3 -> 2 is printed then the whole array is flipped: : {5, 4, 3, 2, 1, 0} -> {0, 1, 2, 3, 4, 5} 
                      On 2nd iteration element on index 4 -> 4 is printed then the whole array is flipped:  {0, 1, 2, 3, 4, 5} -> {5, 4, 3, 2, 1, 0} 
                      On 2nd iteration element on index 5 -> 0 is printed then the whole array is flipped: : {5, 4, 3, 2, 1, 0} -> {0, 1, 2, 3, 4, 5} 

Input: arr = {0, 1, 2, 3, 4}
Output: 0 3 2 1 4

 

Approach: The given problem can be solved by using the two-pointer technique. The idea is to iterate the array from left to right starting from the first index, and from right to left starting from the second last index. 

Below steps can be followed to solve the problem:

  • Use pointer one to iterate the array from left to right, and use pointer two to traverse the array from right to left
  • Print the elements pointed by both the pointers simultaneously and increment pointer one by 2 and decrement pointer two by 2

Below is the implementation of the above approach:

C++




// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to print array elements at
// every index by flipping whole array
// after printing every element
void printFlip(vector<int> arr)
{
 
    // Initialize length of the array
    int N = arr.size();
 
    // Initialize both the pointers
    int p1 = 0, p2 = N - 2;
 
    // Iterate until both pointers
    // are not out of bounds
    while (p1 < N || p2 >= 0) {
 
        // Print the elements
        cout << arr[p1] << " ";
        if (p2 > 0)
            cout << arr[p2] << " ";
 
        // Increment p1 by 2
        p1 += 2;
 
        // Decrement p2 by 2
        p2 -= 2;
    }
}
 
// Driver code
int main()
{
 
    // Initialize the array
    vector<int> arr = { 0, 1, 2, 3, 4 };
 
    // Call the function
    // and print the array
    printFlip(arr);
    return 0;
}
 
// This code is contributed by Potta Lokesh.
 
 

Java




// Java implementation for the above approach
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to print array elements at
    // every index by flipping whole array
    // after printing every element
    public static void printFlip(int[] arr)
    {
 
        // Initialize length of the array
        int N = arr.length;
 
        // Initialize both the pointers
        int p1 = 0, p2 = N - 2;
 
        // Iterate until both pointers
        // are not out of bounds
        while (p1 < N || p2 >= 0) {
 
            // Print the elements
            System.out.print(arr[p1] + " ");
            if (p2 > 0)
                System.out.print(arr[p2] + " ");
 
            // Increment p1 by 2
            p1 += 2;
 
            // Decrement p2 by 2
            p2 -= 2;
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        // Initialize the array
        int[] arr = { 0, 1, 2, 3, 4 };
 
        // Call the function
        // and print the array
        printFlip(arr);
    }
}
 
 

Python3




# Python code for the above approach
 
# Function to print array elements at
# every index by flipping whole array
# after printing every element
def printFlip(arr):
 
    # Initialize length of the array
    N = len(arr);
 
    # Initialize both the pointers
    p1 = 0
    p2 = N - 2;
 
    # Iterate until both pointers
    # are not out of bounds
    while (p1 < N or p2 >= 0):
 
        # Print the elements
        print(arr[p1], end=" ");
        if (p2 > 0):
            print(arr[p2], end=" ");
 
        # Increment p1 by 2
        p1 += 2;
 
        # Decrement p2 by 2
        p2 -= 2;
     
# Driver Code
# Initialize the array
arr = [ 0, 1, 2, 3, 4 ];
 
# Call the function
# and print the array
printFlip(arr);
 
# This code is contributed by gfgking.
 
 

C#




// C# implementation for the above approach
using System;
 
class GFG {
 
    // Function to print array elements at
    // every index by flipping whole array
    // after printing every element
    static void printFlip(int []arr)
    {
 
        // Initialize length of the array
        int N = arr.Length;
 
        // Initialize both the pointers
        int p1 = 0, p2 = N - 2;
 
        // Iterate until both pointers
        // are not out of bounds
        while (p1 < N || p2 >= 0) {
 
            // Print the elements
            Console.Write(arr[p1] + " ");
            if (p2 > 0)
                Console.Write(arr[p2] + " ");
 
            // Increment p1 by 2
            p1 += 2;
 
            // Decrement p2 by 2
            p2 -= 2;
        }
    }
 
    // Driver code
    public static void Main()
    {
 
        // Initialize the array
        int []arr = { 0, 1, 2, 3, 4 };
 
        // Call the function
        // and print the array
        printFlip(arr);
    }
}
// This code is contributed by Samim Hossain Mondal.
 
 

Javascript




<script>
// Javascript code for the above approach
 
// Function to print array elements at
// every index by flipping whole array
// after printing every element
function printFlip(arr)
{
 
    // Initialize length of the array
    let N = arr.length;
 
    // Initialize both the pointers
    let p1 = 0, p2 = N - 2;
 
    // Iterate until both pointers
    // are not out of bounds
    while (p1 < N || p2 >= 0) {
 
        // Print the elements
        document.write(arr[p1] + " ");
        if (p2 > 0)
            document.write(arr[p2] + " ");
 
        // Increment p1 by 2
        p1 += 2;
 
        // Decrement p2 by 2
        p2 -= 2;
    }
}
 
// Driver Code
// Initialize the array
let arr = [ 0, 1, 2, 3, 4 ];
 
// Call the function
// and print the array
printFlip(arr);
 
// This code is contributed by Samim Hossain Mondal.
</script>
 
 

 
 

Output
0 3 2 1 4 

 

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

 



Next Article
Array obtained by repeatedly reversing array after every insertion from given array

B

bedisanam
Improve
Article Tags :
  • Arrays
  • C/C++ Puzzles
  • DSA
  • Dynamic Programming
  • two-pointer-algorithm
Practice Tags :
  • Arrays
  • Dynamic Programming
  • two-pointer-algorithm

Similar Reads

  • 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
  • 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 the original array from given array obtained after P prefix reversals
    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 =
    10 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
  • 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
  • Reverse the elements only at odd positions in the given Array
    Given an array arr[] containing N integers, the task is to rearrange the array such that the odd indexed elements are in reverse order. Examples: Input: arr[] = {5, 7, 6, 2, 9, 18, 11, 15} Output: {5, 15, 6, 18, 9, 2, 11, 7} Explanation: The elements at even index [5, 6, 9, 11] are unchanged and ele
    6 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
  • Count remaining array elements after reversing binary representation of each array element
    Given an array arr[] consisting of N positive integers, the task is to modify every array element by reversing them binary representation and count the number of elements in the modified array that were also present in the original array. Examples: Input: arr[] = {2, 4, 5, 20, 16} Output: 2Explanati
    8 min read
  • 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
  • Find the final sequence of the array after performing given operations
    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[]. Finally, print the contents of the list b[] after the end of all operations.Exam
    12 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