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:
Reverse an Array in groups of given size
Next article icon

Reverse an array upto a given position

Last Updated : 13 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] and a position in array, k. Write a function name reverse (a[], k) such that it reverses subarray arr[0..k-1]. Extra space used should be O(1) and time complexity should be O(k). 
Example: 

Input: arr[] = {1, 2, 3, 4, 5, 6}     k = 4  Output: arr[] = {4, 3, 2, 1, 5, 6} 

We strongly recommend you to minimize your browser and try this yourself first.

Below is the implementation for the same. 

C++




// C++ program to reverse a subarray arr[0..k-1]
#include <bits/stdc++.h>
using namespace std;
 
// Reverse subarray a[0..k-1]
void reverse(int a[], int n, int k)
{
    if (k > n)
    {
        cout << "Invalid k";
        return;
    }
 
    // One by one reverse first and last elements of a[0..k-1]
    for (int i = 0; i < k/2; i++)
        swap(a[i], a[k-i-1]);
}
 
// Driver program
int main()
{
    int a[] = {1, 2, 3, 4, 5, 6};
    int n = sizeof(a) / sizeof(int), k = 4;
 
    reverse(a, n, k);
 
    for (int i = 0; i < n; ++i)
        printf("%d ", a[i]);
 
    return 0;
}
 
 

Java




// java program to reverse a
// subarray arr[0..k-1]
 
public class GFG {
 
    // Reverse subarray a[0..k-1]
    static void reverse(int []a, int n, int k)
    {
        if (k > n)
        {
            System.out.println( "Invalid k");
            return;
        }
     
        // One by one reverse first
        // and last elements of a[0..k-1]
        for (int i = 0; i < k / 2; i++)
        {
            int tempswap = a[i];
                a[i] = a[k - i - 1];
                a[k - i - 1] = tempswap;            
        }
    }
 
    // Driver code
    public static void main(String args[])
    {
        int []a = {1, 2, 3, 4, 5, 6};
        int n = a.length, k = 4;
        reverse(a, n, k);
        for (int i = 0; i < n; ++i)
            System.out.print(a[i] + " ");
    }
}
 
// This code is contributed by Sam007.
 
 

Python3




# python program to reverse a subarray
# arr[0..k-1]
from __future__ import print_function
 
# Reverse subarray a[0..k-1]
def reverse(a, n, k):
     
    if (k > n):
        print( "Invalid k")
        return
     
    # One by one reverse first and
    # last elements of a[0..k-1]
    for i in range(0, (int)(k/2)):
        temp = a[i]
        a[i] = a[k-i-1]
        a[k-i-1] = temp
         
# Driver program
a = [1, 2, 3, 4, 5, 6]
n = len(a)
k = 4
 
reverse(a, n, k);
 
for i in range(0, n):
    print(a[i], end=" ")
     
# This code is contributed by Sam007.
 
 

C#




// C# program to reverse a
// subarray arr[0..k-1]
using System;
 
class GFG {
     
static void SwapNum(ref int x, ref int y)
{
    int tempswap = x;
    x = y;
    y = tempswap;            
}
     
// Reverse subarray a[0..k-1]
static void reverse(int []a, int n,
                             int k)
{
    if (k > n)
    {
        Console.Write( "Invalid k");
        return;
    }
 
    // One by one reverse first
    // and last elements of a[0..k-1]
    for (int i = 0; i < k / 2; i++)
        SwapNum(ref a[i], ref a[k - i - 1]);
         
}
 
// Driver Code
public static void Main()
{
    int []a = {1, 2, 3, 4, 5, 6};
    int n = a.Length, k = 4;
 
    reverse(a, n, k);
 
    for (int i = 0; i < n; ++i)
        Console.Write(a[i] + " ");
}
}
 
// This code is contributed by Sam007
 
 

Javascript




<script>
 
// Javascript program to reverse
// a subarray arr[0..k-1]
 
// Reverse subarray a[0..k-1]
function reverse( a, n, k)
{
    if (k > n)
    {
        document.write("Invalid k");
        return;
    }
 
    // One by one reverse first
    // and last elements of a[0..k-1]
    for (let i = 0; i < Math.floor(k/2); i++)
    {
      let temp = a[i] ;
      a[i] = a[k-i-1] ;
      a[k-i-1] = temp ;
    }
     
}
    // driver code
     
    let a = [1, 2, 3, 4, 5, 6];
    let n = a.length, k = 4;
 
    reverse(a, n, k);
 
    for (let i = 0; i < n; ++i)
        document.write(a[i] + " ");
 
</script>
 
 
Output
4 3 2 1 5 6 

Time complexity: O(k)

Auxiliary Space: O(1) ,since extra space is used.

Method 2 (using STL):

In this method we will use an in-built C++ STL function named reverse. This function completes the task of reversing K elements of array in O(K) time and also doesn’t use extra space.

implementation of this method is below.

C++




// C++ program to reverse the first K
// elements using in-built function
#include <bits/stdc++.h>
using namespace std;
int main()
{
 
    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
    int k = 4;
 
    // STL function to reverse element
    // from 0 index to K-1 index.
    reverse(arr, arr + k);
    // printing the array after reversing
    // first K elements.
    for (int i = 0; i < 8; i++) {
        cout << arr[i] << " ";
    }
    return 0;
}
 
// this code is contributed by Machhaliya Muhammad
 
 

Java




// Java program to reverse the first K
// elements using in-built function
 
import java.io.*;
import java.util.*;
import java.util.Arrays;
 
class GFG {
    public static void main (String[] args) {
    Integer[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 };
    int k = 4;
 
    // Java Library function to reverse element
    // from 0 index to K-1 index.
    Integer[] arr1 = Arrays.copyOfRange(arr, 0, k);  
    Collections.reverse(Arrays.asList(arr1));
    System.arraycopy(arr1, 0, arr, 0, k); 
 
    // printing the array after reversing
    // first K elements.
    for (int i = 0; i < 8; i++) {
    System.out.print(arr[i] + " ");
    }
    }
}
 
// This code is contributed by Aman Kumar.
 
 

Python3




# Python3 program to reverse the first K
# elements using in-built function
arr = [ 1, 2, 3, 4, 5, 6, 7, 8 ]
k = 4
 
# Using list slicing to reverse the array
# from 0 index to K-1 index.
arr[:k] = arr[:k][::-1]
 
# printing the array after reversing
# first K elements.
print(*arr)
 
# This code is contributed by phasing17
 
 

C#




// C# program to reverse the first K
// elements using in-built function
using System;
using System.Collections.Generic;
 
class GFG
{
  public static void Main(string[] args)
  {
    int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 };
    int k = 4;
 
    // C# Library function to reverse element
    // from 0 index to K-1 index.
    Array.Reverse(arr, 0, k);
 
    // printing the array after reversing
    // first K elements.
    for (int i = 0; i < 8; i++) {
      Console.Write(arr[i] + " ");
    }
  }
}
 
// this code is contributed by phasing17
 
 

Javascript




// JavaScript program to reverse the first K
// elements using in-built functions
let arr = [ 1, 2, 3, 4, 5, 6, 7, 8 ];
let k = 4;
 
// Library function to reverse element
// from 0 index to K-1 index.
let arr1 = arr.slice(0, k);
arr1.reverse();
arr.splice(0, k, ...arr1);
 
// printing the array after reversing
// first K elements.
for (var i = 0; i < 8; i++)
    process.stdout.write(arr[i] + " ");
 
// This code is contributed by phasing17
 
 
Output
4 3 2 1 5 6 7 8 

Time Complexity :O(K) , as complexity of reverse() function is O(number of elements of array to be sorted).

Auxiliary Space :O(1),  as no extra space used.



Next Article
Reverse an Array in groups of given size
author
kartik
Improve
Article Tags :
  • Arrays
  • C++
  • DSA
  • Amazon
  • Reverse
Practice Tags :
  • Amazon
  • CPP
  • Arrays
  • Reverse

Similar Reads

  • Reverse an Array without changing position of zeroes
    Given an array arr[] and N, which is the size of this array, the task is to reverse this array without changing the position of zeroes in this array. Examples: Input: arr[] = {0, 3, 0, 6, 0, 8}, N = 6Output: [0, 8, 0, 6, 0, 3]Explanation: The position of the zeroes is not disturbed. Input: arr[] = {
    6 min read
  • Reverse an Array in groups of given size
    Given an array arr[] and an integer k, the task is to reverse every subarray formed by consecutive K elements. Examples: Input: arr[] = [1, 2, 3, 4, 5, 6, 7, 8, 9], k = 3 Output: 3, 2, 1, 6, 5, 4, 9, 8, 7 Input: arr[] = [1, 2, 3, 4, 5, 6, 7, 8], k = 5 Output: 5, 4, 3, 2, 1, 8, 7, 6 Input: arr[] = [1
    6 min read
  • Reorder an array according to given indexes
    Given two integer arrays of the same length, arr[] and index[], the task is to reorder the elements in arr[] such that after reordering, each element from arr[i] moves to the position index[i]. The new arrangement reflects the values being placed at their target indices, as described by index[] arra
    15+ min read
  • Search an element in a reverse sorted array
    Given an array arr[] sorted in decreasing order, and an integer X, the task is to check if X is present in the given array or not. If X is present in the array, print its index ( 0-based indexing). Otherwise, print -1. Examples: Input: arr[] = {5, 4, 3, 2, 1}, X = 4Output: 1Explanation: Element X (=
    8 min read
  • Program to reverse columns in given 2D Array (Matrix)
    Given a 2D array arr[][]of integers of size M x N, where N is the number of columns and M is the number of rows in the array. The task is to reverse every column of the given 2D array Input: arr[][] = {{3, 2, 1} {4, 5, 6}, {9, 8, 7}} Output: 9 8 7 4 5 6 3 2 1 Input: arr[][] = {{7, 9}, {1, 5}, {4, 6}
    7 min read
  • Program to reverse an array using pointers
    Prerequisite : Pointers in C/C++ Given an array, write a program to reverse it using pointers . In this program we make use of * operator . The * (asterisk) operator denotes the value of variable . The * operator at the time of declaration denotes that this is a pointer, otherwise it denotes the val
    4 min read
  • Perl | Reverse an array
    Reverse an array or string in Perl. Iterative Way: Iterate over the array from 0 to mid of array. Swap the arr[i] element with arr[size-i] element. #Perl code to reverse an array iteratively #declaring an array of integers @arr = (2, 3, 4, 5, 6, 7); # Store length on array in $n variable $n = $#arr;
    2 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
  • Reverse an array in groups of given size | Set 2 (Variations of Set 1 )
    Given an array, reverse every sub-array that satisfies the given constraints.We have discussed a solution where we reverse every sub-array formed by consecutive k elements in Set 1. In this set, we will discuss various interesting variations of this problem. Variation 1 (Reverse Alternate Groups): R
    15+ min read
  • Reverse an array in groups of given size | Set 3 (Single traversal)
    Given an array, reverse every sub-array formed by consecutive k elements. Examples: Input: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3. Output: [3, 2, 1, 6, 5, 4, 9, 8, 7, 10]Input: arr = [1, 2, 3, 4, 5, 6, 7], k = 5. Output: [5, 4, 3, 2, 1, 7, 6] Approach: We will use two pointers technique to sol
    6 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