The Wayback Machine - https://web.archive.org/web/20240818163950/https://www.geeksforgeeks.org/program-to-reverse-an-array/
Open In App

Array Reverse in C/C++/Java/Python/JavaScript

Last Updated : 05 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Reversing an array means changing the position of each number in the array to its corresponding position from the end. For example, if a number is at position 1, its new position will be at Array.length, and similarly, if a number is at position 2, its new position will be at Array.length – 1, and so on.

Array Reverse in C/C++/Java/Python/JavaScript

Array Reverse in C/C++/Java/Python/JavaScript

To deepen your understanding of array manipulation and other critical concepts in data structures and algorithms , consider learning from the Complete Data Structures and Algorithms (DSA) Course . This comprehensive course covers a wide range of topics, including array manipulation, linked lists, stacks, queues, trees, graphs, and advanced algorithms.

Given an array (or string), the task is to reverse the array/string.

Examples:

Input: original_array[] = {1, 2, 3} Output: array_reversed[] = {3, 2, 1}

Input: original_array[] = {4, 5, 1, 2}
Output: array_reversed[] = {2, 1, 5, 4}

1. Array Reverse Using an Extra Array (Non In-place):

  • Create a new array of the same size as the original array.
  • Copy elements from the original array to the new array in reverse order.

Below is the implementation of the above approach:

C++
#include <iostream>;
using namespace std;

void reverseArrayExtraArray(int arr[], int size)
{
    int reversedArr[size];
    for (int i = 0; i < size; i++) {
        reversedArr[i] = arr[size - i - 1];
    }

    // Print reversed array
    cout << "Reversed Array: ";
    for (int i = 0; i < size; i++) {
        std::cout << reversedArr[i] << " ";
    }
}

int main()
{
    int originalArr[] = { 1, 2, 3, 4, 5 };
    int size = sizeof(originalArr) / sizeof(originalArr[0]);

    reverseArrayExtraArray(originalArr, size);
}
C
#include <stdio.h>

void reverseArrayExtraArray(int arr[], int size)
{
    int reversedArr[size];
    for (int i = 0; i < size; i++) {
        reversedArr[i] = arr[size - i - 1];
    }

    // Print reversed array
    printf("Reversed Array: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", reversedArr[i]);
    }
}

int main()
{
    int originalArr[] = { 1, 2, 3, 4, 5 };
    int size = sizeof(originalArr) / sizeof(originalArr[0]);

    reverseArrayExtraArray(originalArr, size);

    return 0;
}
Java
/*package whatever //do not write package name here */

import java.io.*;
public class ReverseArrayExtraArray {
    public static void reverseArrayExtraArray(int[] arr)
    {
        int[] reversedArr = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            reversedArr[i] = arr[arr.length - i - 1];
        }

        // Print reversed array
        System.out.print("Reversed Array: ");
        for (int i : reversedArr) {
            System.out.print(i + " ");
        }
    }

    public static void main(String[] args)
    {
        int[] originalArr = { 1, 2, 3, 4, 5 };
        reverseArrayExtraArray(originalArr);
    }
}
Python
def reverse_array_extra_array(arr):
    reversed_arr = arr[::-1]

    # Print reversed array
    print("Reversed Array:", end=" ")
    for i in reversed_arr:
        print(i, end=" ")

# Example usage:
original_arr = [1, 2, 3, 4, 5]
reverse_array_extra_array(original_arr)
C#
using System;

class Program {
    static void ReverseArrayExtraArray(int[] arr) {
        int[] reversedArr = new int[arr.Length];
        for (int i = 0; i < arr.Length; i++) {
            reversedArr[i] = arr[arr.Length - i - 1];
        }

        // Print reversed array
        Console.Write("Reversed Array: ");
        foreach (int num in reversedArr) {
            Console.Write(num + " ");
        }
    }

    static void Main() {
        int[] originalArr = {1, 2, 3, 4, 5};
        ReverseArrayExtraArray(originalArr);
    }
}
JavaScript
function reverseArrayExtraArray(arr) {
    const reversedArr = arr.slice().reverse();

    // Print reversed array
    process.stdout.write("Reversed Array: ");
    reversedArr.forEach(element => process.stdout.write(element + " "));
}

// Example usage:
const originalArr = [1, 2, 3, 4, 5];
reverseArrayExtraArray(originalArr);

Output
Reversed Array: 5 4 3 2 1 
  • Time Complexity: O(n)
    • Copying elements to a new array is a linear operation.
  • Auxiliary Space Complexity: O(n)
    • Additional space is used to store the new array.

2. Array Reverse Using a Loop (In-place):

  • Iterate through the array using two pointers (start and end).
  • Swap elements at the start and end pointers.
  • Move the start pointer towards the end and the end pointer towards the start until they meet or cross each other.

reverse-a-number

Below is the implementation of the above approach :

C++
// Iterative C++ program to reverse an array
#include <bits/stdc++.h>;
using namespace std;

/* Function to reverse arr[] from start to end*/
void reverseArray(int arr[], int start, int end)
{
    while (start < end) {
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}

/* Utility function to print an array */
void printArray(int arr[], int size)
{
    for (int i = 0; i < size; i++)
        cout << arr[i] << " ";

    cout << endl;
}

/* Driver function to test above functions */
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6 };

    int n = sizeof(arr) / sizeof(arr[0]);

    // To print original array
    printArray(arr, n);

    // Function calling
    reverseArray(arr, 0, n - 1);

    cout << "Reversed array is" << endl;

    // To print the Reversed array
    printArray(arr, n);

    return 0;
}
C
// Iterative C program to reverse an array
#include <stdio.h>

/* Function to reverse arr[] from start to end*/
void reverseArray(int arr[], int start, int end)
{
    int temp;
    while (start < end) {
        temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}

/* Utility that prints out an array on a line */
void printArray(int arr[], int size)
{
    int i;
    for (i = 0; i < size; i++)
        printf("%d ", arr[i]);

    printf("\n");
}

/* Driver function to test above functions */
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printArray(arr, n);
    reverseArray(arr, 0, n - 1);
    printf("Reversed array is \n");
    printArray(arr, n);
    return 0;
}
Java
public class GFG { 
    /* Function to reverse arr[] from start to end*/
    static void reverseArray(int arr[], int start, int end) { 
        int temp; 
        while (start < end) { 
            temp = arr[start]; 
            arr[start] = arr[end]; 
            arr[end] = temp; 
            start++; 
            end--; 
        } 
    } 

    /* Utility that prints out an array on a line */
    static void printArray(int arr[], int size) { 
        for (int i = 0; i < size; i++) 
            System.out.print(arr[i] + " "); 
        System.out.println(); 
    } 

    // Driver code 
    public static void main(String args[]) { 
        int arr[] = {1, 2, 3, 4, 5, 6}; 
        printArray(arr, 6); 
        reverseArray(arr, 0, 5); 
        System.out.print("Reversed array is \n"); 
        printArray(arr, 6); 
    } 
}
Python
# Iterative python program to reverse an array

# Function to reverse A[] from start to end


def reverseList(A, start, end):
    while start < end:
        A[start], A[end] = A[end], A[start]
        start += 1
        end -= 1


# Driver function to test above function
A = [1, 2, 3, 4, 5, 6]
print(A)
reverseList(A, 0, 5)
print("Reversed list is")
print(A)
# This program is contributed by Pratik Chhajer
C#
// Iterative C# program to reverse an
// array
using System;

class GFG {

    /* Function to reverse arr[] from
    start to end*/
    static void reverseArray(int[] arr, int start, int end)
    {
        int temp;

        while (start < end) {
            temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            start++;
            end--;
        }
    }

    /* Utility that prints out an
    array on a line */
    static void printArray(int[] arr, int size)
    {
        for (int i = 0; i < size; i++)
            Console.Write(arr[i] + " ");

        Console.WriteLine();
    }

    // Driver function
    public static void Main()
    {
        int[] arr = { 1, 2, 3, 4, 5, 6 };
        printArray(arr, 6);
        reverseArray(arr, 0, 5);
        Console.Write("Reversed array is \n");
        printArray(arr, 6);
    }
}

// This code is contributed by Sam007
JavaScript
// Iterative Javascript program to reverse an array 

/* Function to reverse arr[] from start to end*/
function reverseArray(arr,start,end) 
{ 
    while (start < end) 
    { 
        var temp = arr[start]; 
        arr[start] = arr[end]; 
        arr[end] = temp; 
        start++; 
        end--; 
    } 
}     

/* Utility function to print an array */
function printArray(arr,size) 
{ 
for (var i = 0; i < size; i++){ 
console.log(arr[i]); 
} 
} 

/* Driver function to test above functions */
    var arr= [1, 2, 3, 4, 5, 6]; 
    var n = 6; 
    // To print original array 
    printArray(arr, n); 
    
    // Function calling 
    reverseArray(arr, 0, n-1); 
    
    console.log("Reversed array is"); 
    printArray(arr, n); 
PHP
<?php 
// Iterative PHP program 
// to reverse an array 

/* Function to reverse 
$arr from start to end*/
function reverseArray(&$arr, $start, $end) 
{ 
    while ($start < $end) 
    { 
        $temp = $arr[$start]; 
        $arr[$start] = $arr[$end]; 
        $arr[$end] = $temp; 
        $start++; 
        $end--; 
    } 
}     

/* Utility function to 
print an array */
function printArray(&$arr, $size) 
{ 
    for ($i = 0; $i < $size; $i++) 
        echo $arr[$i] . " "; 

    echo "\n"; 
} 

// Driver code 
$arr = array(1, 2, 3, 4, 5, 6); 

// To print original array 
printArray($arr, 6); 

// Function calling 
reverseArray($arr, 0, 5); 

echo "Reversed array is" ."\n"; 

// To print the Reversed array 
printArray($arr, 6); 

// This code is contributed 
// by ChitraNayal 
?>

Output
1 2 3 4 5 6 
Reversed array is
6 5 4 3 2 1 
  • Time Complexity: O(n)
    • The loop runs through half of the array, so it’s linear with respect to the array size.
  • Auxiliary Space Complexity: O(1)
    • In-place reversal, meaning it doesn’t use additional space.

3. Array Reverse Inbuilt Methods (In-place):

  • Use inbuilt methods like reverse in Python or Array.Reverse in C#.

Below is the implementation of the above approach :

C++
#include <algorithm> // for std::reverse
#include <iostream>

int main()
{
    int originalArray[] = { 1, 2, 3, 4, 5 };
    int length
        = sizeof(originalArray) / sizeof(originalArray[0]);

    // Using inbuilt method in C++
    std::reverse(originalArray, originalArray + length);

    // Print the reversed array
    for (int i = 0; i < length; i++) {
        std::cout << originalArray[i] << " ";
    }

    return 0;
}
Java
/*package whatever //do not write package name here */

import java.util.Arrays;

public class ArrayReverse {
    public static void main(String[] args)
    {
        int[] originalArray = { 1, 2, 3, 4, 5 };

        // Using inbuilt method in Java
        int[] reversedArray = new int[originalArray.length];
        for (int i = 0; i < originalArray.length; i++) {
            reversedArray[i]
                = originalArray[originalArray.length - 1
                                - i];
        }

        // Print the reversed array
        System.out.println(Arrays.toString(reversedArray));
    }
}
Python
original_array = [1, 2, 3, 4, 5]

# Using inbuilt method in Python
reversed_array = list(reversed(original_array))

# Print the reversed array
print(reversed_array)
C#
using System;

class Program {
    static void Main()
    {
        int[] originalArray = { 1, 2, 3, 4, 5 };

        // Using inbuilt method in C#
        Array.Reverse(originalArray);

        // Print the reversed array
        foreach(int num in originalArray)
        {
            Console.Write(num + " ");
        }
    }
}
JavaScript
let originalArray = [1, 2, 3, 4, 5];

// Using inbuilt method in JavaScript
let reversedArray = originalArray.slice().reverse();

// Print the reversed array
console.log(reversedArray);

Output
5 4 3 2 1 
  • Time Complexity: O(n) The reverse method typically has linear time complexity.
  • Auxiliary Space Complexity: O(1)
    • Additional space is not used to store the reversed array, as the in-built array method “reverse()” swaps the values in a given range in in-place fashion.

4. Array Reverse Recursion (In-place or Non In-place):

  • Define a recursive function that takes an array as input.
  • Swap the first and last elements.
  • Recursively call the function with the remaining subarray.

Below is the implementation of the above approach :

C++
// Recursive C++ program to reverse an array
#include <bits/stdc++.h>;
using namespace std;

/* Function to reverse arr[] from start to end*/
void reverseArray(int arr[], int start, int end)
{
    if (start >= end)
        return;

    int temp = arr[start];
    arr[start] = arr[end];
    arr[end] = temp;

    // Recursive Function calling
    reverseArray(arr, start + 1, end - 1);
}

/* Utility function to print an array */
void printArray(int arr[], int size)
{
    for (int i = 0; i < size; i++)
        cout << arr[i] << " ";

    cout << endl;
}

/* Driver function to test above functions */
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6 };

    // To print original array
    printArray(arr, 6);

    // Function calling
    reverseArray(arr, 0, 5);

    cout << "Reversed array is" << endl;

    // To print the Reversed array
    printArray(arr, 6);

    return 0;
}
C
// Recursive C program to reverse an array
#include <stdio.h>;

/* Function to reverse arr[] from start to end*/
void reverseArray(int arr[], int start, int end)
{
    int temp;
    if (start >= end)
        return;
    temp = arr[start];
    arr[start] = arr[end];
    arr[end] = temp;
    reverseArray(arr, start + 1, end - 1);
}

/* Utility that prints out an array on a line */
void printArray(int arr[], int size)
{
    int i;
    for (i = 0; i < size; i++)
        printf("%d ", arr[i]);

    printf("\n");
}

/* Driver function to test above functions */
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    printArray(arr, 6);
    reverseArray(arr, 0, 5);
    printf("Reversed array is \n");
    printArray(arr, 6);
    return 0;
}
Java
/*package whatever //do not write package name here */

import java.io.*;

class ReverseArray {

    /* Function to reverse arr[] from start to end*/
    static void reverseArray(int arr[], int start, int end)
    {
        int temp;
        if (start >= end)
            return;
        temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        reverseArray(arr, start + 1, end - 1);
    }

    /* Utility that prints out an array on a line */
    static void printArray(int arr[], int size)
    {
        for (int i = 0; i < size; i++)
            System.out.print(arr[i] + " ");
        System.out.println("");
    }

    /*Driver function to check for above functions*/
    public static void main(String[] args)
    {
        int arr[] = { 1, 2, 3, 4, 5, 6 };
        printArray(arr, 6);
        reverseArray(arr, 0, 5);
        System.out.println("Reversed array is ");
        printArray(arr, 6);
    }
}
/*This article is contributed by Devesh Agrawal*/
Python
# Recursive python program to reverse an array

# Function to reverse A[] from start to end


def reverseList(A, start, end):
    if start >= end:
        return
    A[start], A[end] = A[end], A[start]
    reverseList(A, start+1, end-1)


# Driver function to test above function
A = [1, 2, 3, 4, 5, 6]
print(A)
reverseList(A, 0, 5)
print("Reversed list is")
print(A)
# This program is contributed by Pratik Chhajer
C#
// C# program to reverse an array
using System;

class GFG {
    /* Function to reverse arr[]
    from start to end*/
    static void reverseArray(int[] arr, int start, int end)
    {
        int temp;
        if (start >= end)
            return;

        temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;

        reverseArray(arr, start + 1, end - 1);
    }

    /* Utility that prints out an
    array on a line */
    static void printArray(int[] arr, int size)
    {
        for (int i = 0; i < size; i++)
            Console.Write(arr[i] + " ");

        Console.WriteLine("");
    }

    // Driver Code
    public static void Main()
    {
        int[] arr = { 1, 2, 3, 4, 5, 6 };

        printArray(arr, 6);
        reverseArray(arr, 0, 5);

        Console.WriteLine("Reversed array is ");
        printArray(arr, 6);
    }
}

// This code is contributed by Sam007
JavaScript
// Recursive Javascript program to reverse an array 

/* Function to reverse arr[] from start to end*/
function reverseArray(arr,start,end) 
{ 
    var temp = arr[start]; 
    arr[start] = arr[end]; 
    arr[end] = temp; 
    
// Recursive Function calling 
    if (start+1<end-1){ 
    reverseArray(arr, start + 1, end - 1); 
    } 
}     
/* Utility function to print an array */
function printArray(arr,size) 
{ 
for (var i = 0; i < size; i++){ 
console.log(arr[i]); 
} 
} 

/* Driver function to test above functions */

    var arr= [1, 2, 3, 4, 5, 6]; 
    
    // To print original array 
    printArray(arr, 6); 
    
    // Function calling 
    reverseArray(arr, 0, 5); 
    
    console.log("Reversed array is"); 
    
    // To print the Reversed array 
    printArray(arr, 6); 
PHP
<?php
// Recursive PHP program to reverse an array

/* Function to reverse $arr[] from $start to $end */
function reverseArray(&$arr, $start, $end) 
{ 
    if ($start >= $end) {
        return;
    }
    
    $temp = $arr[$start]; 
    $arr[$start] = $arr[$end]; 
    $arr[$end] = $temp; 
    
    // Recursive Function calling 
    reverseArray($arr, $start + 1, $end - 1); 
} 

/* Utility function to print an array */
function printArray(&$arr, $size) 
{ 
    for ($i = 0; $i < $size; $i++) {
        echo $arr[$i] . " "; 
    }
    echo "\n"; 
} 

// Driver function to test above functions
$arr = array(1, 2, 3, 4, 5, 6); 

// To print original array 
printArray($arr, 6); 

// Function calling 
reverseArray($arr, 0, 5); 

echo "Reversed array is" . "\n"; 

// To print the Reversed array 
printArray($arr, 6); 
?>

Output
1 2 3 4 5 6 
Reversed array is
6 5 4 3 2 1 
  • Time Complexity: O(n). The recursion goes through each element once, so it’s linear.
  • Auxiliary Space Complexity: O(n) for non in-place, O(log n) for in-place (due to recursion stack).

5. Array Reverse Stack (Non In-place):

  • Push each element of the array onto a stack.
  • Pop elements from the stack to form the reversed array.

Below is the implementation of the above approach :

C++
#include <iostream>;
#include <stack>;
#include <vector>;

void reverseArrayUsingStack(int arr[], int size)
{
    std::stack<int> stack;

    // Push elements onto the stack
    for (int i = 0; i < size; i++) {
        stack.push(arr[i]);
    }

    // Pop elements from the stack to reverse the array
    for (int i = 0; i < size; i++) {
        arr[i] = stack.top();
        stack.pop();
    }
}

int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int size = sizeof(arr) / sizeof(arr[0]);

    reverseArrayUsingStack(arr, size);

    std::cout << "Reversed Array: ";
    for (int i = 0; i < size; i++) {
        std::cout << arr[i] << " ";
    }

    return 0;
}
C
#include <stdio.h>;
#include <stdlib.h>;

#define MAX_SIZE 100

struct Stack {
    int arr[MAX_SIZE];
    int top;
};

void push(struct Stack* stack, int element)
{
    if (stack->top == MAX_SIZE - 1) {
        printf("Stack Overflow\n");
        return;
    }
    stack->arr[++stack->top] = element;
}

int pop(struct Stack* stack)
{
    if (stack->top == -1) {
        printf("Stack Underflow\n");
        exit(1);
    }
    return stack->arr[stack->top--];
}

void reverseArrayUsingStack(int arr[], int size)
{
    struct Stack stack;
    stack.top = -1;

    // Push elements onto the stack
    for (int i = 0; i < size; i++) {
        push(&stack, arr[i]);
    }

    // Pop elements from the stack to reverse the array
    for (int i = 0; i < size; i++) {
        arr[i] = pop(&stack);
    }
}

int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int size = sizeof(arr) / sizeof(arr[0]);

    reverseArrayUsingStack(arr, size);

    printf("Reversed Array: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}
Java
/*package whatever //do not write package name here */

import java.util.Stack;

public class ReverseArrayUsingStack {
    public static void reverseArrayUsingStack(int[] arr)
    {
        Stack<Integer> stack = new Stack<>();

        // Push elements onto the stack
        for (int element : arr) {
            stack.push(element);
        }

        // Pop elements from the stack to reverse the array
        for (int i = 0; i < arr.length; i++) {
            arr[i] = stack.pop();
        }
    }

    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 3, 4, 5 };

        reverseArrayUsingStack(arr);

        System.out.print("Reversed Array: ");
        for (int element : arr) {
            System.out.print(element + " ");
        }
    }
}
Python
def reverse_array_using_stack(arr):
    stack = []
    
    # Push elements onto the stack
    for element in arr:
        stack.append(element)
    
    # Pop elements from the stack to reverse the array
    for i in range(len(arr)):
        arr[i] = stack.pop()

# Example usage:
arr = [1, 2, 3, 4, 5]
reverse_array_using_stack(arr)
print("Reversed Array:", arr)
C#
using System;
using System.Collections.Generic;

class Program {
    static void ReverseArrayUsingStack(int[] arr)
    {
        Stack<int> stack = new Stack<int>();

        // Push elements onto the stack
        foreach(int element in arr) { stack.Push(element); }

        // Pop elements from the stack to reverse the array
        for (int i = 0; i < arr.Length; i++) {
            arr[i] = stack.Pop();
        }
    }

    static void Main()
    {
        int[] arr = { 1, 2, 3, 4, 5 };

        ReverseArrayUsingStack(arr);

        Console.Write("Reversed Array: ");
        foreach(int element in arr)
        {
            Console.Write(element + " ");
        }
    }
}
JavaScript
function reverseArrayUsingStack(arr) {
    let stack = [];
    
    // Push elements onto the stack
    for (let i = 0; i < arr.length; i++) {
        stack.push(arr[i]);
    }

    // Pop elements from the stack to reverse the array
    for (let i = 0; i < arr.length; i++) {
        arr[i] = stack.pop();
    }
}

// Example usage:
let arr = [1, 2, 3, 4, 5];
reverseArrayUsingStack(arr);
console.log("Reversed Array:", arr);

Output
Reversed Array: 5 4 3 2 1 
  • Time Complexity: O(n)
    • Pushing and popping each element onto/from the stack requires linear time.
  • Auxiliary Space Complexity: O(n)
    • Additional space is used to store the stack.


Previous Article
Next Article

Similar Reads

Count of unique pairs (i, j) in an array such that sum of A[i] and reverse of A[j] is equal to sum of reverse of A[i] and A[j]
Given an array arr[] consisting of N positive integers, the task is to find the count of unique pairs (i, j) such that the sum of arr[i] and the reverse(arr[j]) is the same as the sum of reverse(arr[i]) and arr[j]. Examples: Input: arr[] = {2, 15, 11, 7}Output: 3Explanation:The pairs are (0, 2), (0, 3) and (2, 3). (0, 2): arr[0] + reverse(arr[2]) (
7 min read
Count number of common elements between a sorted array and a reverse sorted array
Given two arrays consisting of N distinct integers such that the array A[] and B[] are sorted in ascending and descending order respectively, the task is to find the number of values common in both arrays. Examples: Input: A[] = {1, 10, 100}, B[] = {200, 20, 2}Output: 0 Input: A[] = {2, 4, 5, 8, 12, 13, 17, 18, 20, 22, 309, 999}, B[] = {109, 99, 68
15+ min read
Sum of integer value of input Array and reverse Array
Given an integer array of numbers num[], the task is to write a function to return the sum of the value of the array with its reverse value and then return the resulting array of digits. Examples: Input: num[] = [2, 5, 8, 2]Output: [5, 4, 3, 4]Explanation: Given array [2, 5, 8, 2], the numerical value is 2582 and the reverse value is 2852, so the s
11 min read
Reverse an array upto a given position
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 yo
6 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 value of the memory location pointed by the pointer .
4 min read
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[] = {2, 0, 5, 0, 7, 0, 3}, N = 6Output: [3, 0, 7, 0, 5,
6 min read
Sorting array with reverse around middle
Consider the given array arr[], we need to find if we can sort array with the given operation. The operation is We have to select a subarray from the given array such that the middle element(or elements (in case of even number of elements)) of subarray is also the middle element(or elements (in case of even number of elements)) of the given array.
6 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; #Print the original array print &quot;The origina
2 min read
Reverse the substrings of the given String according to the given Array of indices
Given a string S and an array of indices A[], the task is to reverse the substrings of the given string according to the given Array of indices.Note: A[i] ? length(S), for all i.Examples: Input: S = "abcdef", A[] = {2, 5} Output: baedcf Explanation: Input: S = "abcdefghij", A[] = {2, 5} Output: baedcjihgf Approach: The idea is to use the concept of
10 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 solve this problem.First, we will initialize our 1st
6 min read
Count pairs in array such that one element is reverse of another
Given an array arr[], the task is to count the pairs in the array such that the elements are the reverse of each other. Examples: Input: arr[] = { 16, 61, 12, 21, 25 } Output: 2 Explanation: The 2 pairs such that one number is the reverse of the other are {16, 61} and {12, 21}. Input: arr[] = {10, 11, 12} Output: 0 Method 1: Approach: The idea is t
14 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 elements at odd index are reversed from [7, 2, 18, 15
6 min read
Reverse a subarray to maximize sum of even-indexed elements of given array
Given an array arr[], the task is to maximize the sum of even-indexed elements by reversing a subarray and print the maximum sum obtained. Examples: Input: arr[] = {1, 2, 1, 2, 1} Output: 5 Explanation: Sum of initial even-indexed elements = a[0] + a[2] + a[4] = 1 + 1 + 1 = 3 Reversing subarray {1, 2, 1, 2} modifies the array to {2, 1, 2, 1, 1}. He
9 min read
Reverse substrings of given string according to specified array indices
Given string str of length N and an array arr[] of integers, for array element arr[i](1-based indexing), reverse the substring in indices [arr[i], N - arr[i] + 1]. The task is to print the string after every reversal. Examples: Input: str = "GeeksforGeeks", arr[] = {2}Output: GkeeGrofskeesExplanation:For first element of the array is 2:Reverse the
7 min read
Reverse an array using Stack
Given an array arr[] of size N, the task to reverse the array using Stack. Examples: Input: arr[] = { 10, 20, 30, 40, 50 } Output: 50 40 30 20 10 Explanation: Reversing the array modifies arr[] to { 50, 40, 30, 20, 10 } Therefore, the required output is 50 40 30 20 10. Input: arr[] = { 1 } Output: 1 Iterative and Recursive Approach: Refer the artic
12 min read
Reverse all elements of given circular array starting from index K
Given a circular array arr[] of size N and an index K, the task is to reverse all elements of the circular array starting from the index K. Examples: Input: arr[] = {3, 5, 2, 4, 1}, K = 2Output: 4 2 5 3 1Explanation:After reversing the elements of the array from index K to K - 1, the modified arr[] is {4, 1, 2, 5, 3}. Input: arr[] = {1, 2, 3, 4, 5}
7 min read
Rearrange given Array by splitting in half and inserting second half in reverse at alternate position
Given an array arr[] of even length N, the task is to perform the following operations on the given array: Split the given array in half.Insert the second half in reverse order at alternate positions from the start. Examples: Input: N = 6, arr[] = {1, 2, 3, 4, 5, 6}Output: 1 6 2 5 3 4Explanation: The first element is 1.Then print the last element 6
5 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}, {19, 3}} Output: 19 3 4 6 1 5 7 9 Program to rev
7 min read
Python Program to Reverse all Prime Numbers in Array Without Affecting Elements
Given an array, our task is to Reverse all prime numbers in an array without affecting other elements in Python. Examples: Input : arr = {1, 2, 3, 4, 5, 6} Output : {1,5,3,4,2,6} Explanation: Prime elements in given array are 2,3,5. After reversing the modified array will be {1,5,3,4,2,6} Approach: Start traversing the array from left to right.Main
3 min read
Reverse a subarray of the given array to minimize the sum of elements at even position
Given an array arr[] of positive integers. The task is to reverse a subarray to minimize the sum of elements at even places and print the minimum sum. Note: Perform the move only one time. Subarray might not be reversed. Example: Input: arr[] = {1, 2, 3, 4, 5} Output: 7 Explanation: Sum of elements at even positions initially = arr[0] + arr[2] + ar
15 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): Reverse every alternate sub-array formed by consecu
15+ min read
Reverse an array without using subtract sign ‘-‘ anywhere in the code
Given an array, the task is to reverse the array without using subtract sign ‘-‘ anywhere in your code. It is not tough to reverse an array but the main thing is to not use '-' operator. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Asked in: Moonfrog Interview Below are different approaches: Method 1: Store ar
11 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 (= 4) is present at index 1.Therefore, the required
8 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, 2, 3, 4, 5, 6], K = 1 Output: 1, 2, 3, 4, 5, 6 I
7 min read
Reverse alternate K nodes in a Singly Linked List
Given a linked list, write a function to reverse every alternate k nodes (where k is an input to the function) in an efficient way. Give the complexity of your algorithm. Example: Inputs: 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;8-&gt;9-&gt;NULL and k = 3 Output: 3-&gt;2-&gt;1-&gt;4-&gt;5-&gt;6-&gt;9-&gt;8-&gt;7-&gt;NULL. Method 1 (Process 2k node
15+ min read
Reverse the order of all nodes at even position in given Linked List
Given a linked list A[] of N integers, the task is to reverse the order of all integers at an even position. Examples: Input: A[] = 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 6 -&gt; NULLOutput: 1 6 3 4 5 2Explanation: Nodes at even position in the given linked list are 2, 4 and 6. So, after reversing there order, the new linked list will be 1 -&gt; 6
10 min read
Reverse a Linked List according to its Size
Given a linked list with n nodes, reverse it in the following way : If n is even, reverse it in a group of n/2 nodes.If n is odd, keep the middle node as it is, reverse first n/2 elements and reverse last n/2 elements. Examples: Input : 1 2 3 4 5 6 (n is even) Output : 3 2 1 6 5 4 Input : 1 2 3 4 5 6 7 (n is odd) Output : 3 2 1 4 7 6 5 Approach: Th
11 min read
Reverse bits of a positive integer number in Python
Given an positive integer and size of bits, reverse all bits of it and return the number with reversed bits.Examples: Input : n = 1, bitSize=32 Output : 2147483648 On a machine with size of bit as 32. Reverse of 0....001 is 100....0. Input : n = 2147483648, bitSize=32 Output : 1 We can solve this problem quickly in Python. Approach is very simple,
4 min read
Reverse Words in a Given String in Python
We are given a string and we need to reverse words of a given string Examples: Input : str =" geeks quiz practice code" Output : str = code practice quiz geeks Input : str = "my name is laxmi" output : str= laxmi is name my Reverse the words in the given string program C/C++ Code # Python code # To reverse words in a given string # input string str
6 min read
Reverse a Doubly linked list using recursion
Given a doubly linked list. Reverse it using recursion. Original Doubly linked list Reversed Doubly linked list We have discussed Iterative solution to reverse a Doubly Linked List Algorithm: If list is empty, return Reverse head by swapping head-&gt;prev and head-&gt;next If prev = NULL it means that list is fully reversed. Else reverse(head-&gt;p
9 min read
three90RightbarBannerImg