![]() |
VOOZH | about |
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]
Table of Content
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.
3 1 2 6 4 5 9 7 8
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
3 1 2 6 4 5 9 7 8
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:
3 1 2 6 4 5 9 7 8