VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-to-reverse-the-rows-in-a-2d-array/

⇱ Program to reverse the rows in a 2d Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to reverse the rows in a 2d Array

Last Updated : 3 Oct, 2025

Given a 2D arrayarr[][] of size M x N integers where M is the number of rows and N is the number of columns. The task is to reverse every row of the given 2D array.
Example:

Input: arr[][] = 
{ {1, 2, 3},
{4, 5, 6},
{7, 8, 9} }
Output:
3 2 1
6 5 4
9 8 7
Input: arr[][] =
{ {1, 2},
{4, 5},
{7, 8},
{9, 10} }
Output:
2 1
5 4
8 7
10 9



Approach:

  1. For every row in the given 2D array do the following: 
    • Initialise the start index as 0 and end index as N-1.
    • Iterate loop till start index is less than ending index, swap the value at these indexes and update the index as: 
swap(arr[i][start], arr[i][end])
start++;
end--;

      2. Do the above operation for all the rows in the 2D array.


Below is the implementation of the above approach: 


Output
3 2 1 
6 5 4 
9 8 7

Time Complexity: O(n*n)

Auxiliary Space: O(1)

Approach#2: Using list comprehension

This approach uses list comprehension to reverse the rows in the input 2D array. It first initializes an empty list and then iterates over each row of the input array, reversing each row using the [::-1] slicing notation and appending the reversed row to the empty list using the append() method. Finally, it prints the reversed array using nested loops.

Algorithm

1. Initialize an empty list.
2. For each row in the input array:
a. Reverse the row using the slicing notation [::-1].
b. Append the reversed row to the empty list using the append() method.
3. Print the reversed array using nested loops.


Output
3 2 1 
6 5 4 
9 8 7 

Time complexity:  O(mn), where m is the number of rows and n is the number of columns in the input array. The code iterates over each element of the input array once to reverse the rows and again to print the reversed array.

Auxiliary Space:  O(mn), where m is the number of rows and n is the number of columns in the input array. The code initializes an empty list of size m and then appends n elements to it for each row of the input array, resulting in a total of m*n elements.

Comment
Article Tags:
Article Tags: