VOOZH about

URL: https://www.geeksforgeeks.org/dsa/shift-matrix-elements-k/

⇱ Shift Matrix Elements row-wise by k - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Shift Matrix Elements row-wise by k

Last Updated : 21 Nov, 2025

Given a square matrix mat[][] and an integer k, shift the first k elements of each row to the end of that row, while keeping the order of the other elements unchanged.

Examples:

Input: k = 2, mat[][] = [[1, 2, 3],
                  [4, 5, 6],
                 [7, 8, 9]]
Output: [[3, 1, 2],
             [6, 4, 5],
             [9, 7, 8]]
Explanation:
For the first row [1, 2, 3], the first k=2 elements [1, 2] are moved to the end, resulting in [3, 1, 2].
For the second row [4, 5, 6], [4, 5] are moved to the end: [6, 4, 5].
For the third row [7, 8, 9], [7, 8] are moved to the end: [9, 7, 8].

Input: k = 2, mat[][] = [[1, 2, 3, 4],
[5, 6, 7, 8],
             [9, 10, 11, 12],
             [13, 14, 15, 16]]
Output: [[3, 4, 1, 2],
[7, 8, 5, 6],
[11, 12, 9, 10],
[15, 16, 13, 14]]
Explanation:
For each row, the first k=2 elements are moved to the end of the row.
[1, 2, 3, 4]: [3, 4, 1, 2]
[5, 6, 7, 8]: [7, 8, 5, 6]
[9, 10, 11, 12]: [11, 12, 9, 10]
[13, 14, 15, 16]: [15, 16, 13, 14]

[Naive Approach] Repeated Left Shifts for Each Row - O(n2 * k) Time and O(1) Space

The simplest way is to process each row independently. For every row, take the first k elements one by one and move them to the end of that row. This can be done by performing k right-shifts: in each shift, remove the first element and append it at the end.


Output
3 1 2 
6 4 5 
9 7 8 

[Expected Approach - 1] Optimized Row-Wise Rotation - O(n2) Time and O(k) Space

Instead of shifting elements one-by-one k times (which is slow), we can perform the shift in one step using slicing.
For each row, split it into two parts:

  • the first k elements
  • the remaining n - k elements

Then simply join them as: newRow = remainingPart + firstKPart


Output
3 1 2 
6 4 5 
9 7 8 

[Expected Approach - 2] Row Rotation Using Reversal - O(n2) Time and O(1) Space

Instead of creating a temporary array to store the first k elements, we can rotate each row in-place by applying the reversal trick.

For each row:

  1. Reverse the first k elements: This flips the segment [0 … k-1].
  2. Reverse the remaining n – k elements: This flips the segment [k … n-1].
  3. Reverse the entire row: After reversing both segments individually, reversing the whole row places everything in its correct rotated position.

Output
3 1 2 
6 4 5 
9 7 8 


Comment
Article Tags: