Skip to content

Commit 511dfa1

Browse files
committed
Add reshape-the-matrix
1 parent 3b352f1 commit 511dfa1

File tree

3 files changed

+39
-1
lines changed

3 files changed

+39
-1
lines changed

Easy/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ Easy
3737
- [remove-duplicates-from-sorted-array.md](Easy/remove-duplicates-from-sorted-array.md)
3838
- [remove-duplicates-from-sorted-list.md](Easy/remove-duplicates-from-sorted-list.md)
3939
- [remove-element.md](Easy/remove-element.md)
40+
- [reshape-the-matrix.md](Easy/reshape-the-matrix.md)
4041
- [reverse-integer.md](Easy/reverse-integer.md)
4142
- [reverse-linked-list.md](Easy/reverse-linked-list.md)
4243
- [roman-to-int.md](Easy/roman-to-int.md)

Easy/reshape-the-matrix.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
Code
2+
====
3+
4+
```go
5+
func matrixReshape(mat [][]int, r int, c int) [][]int {
6+
m := len(mat)
7+
n := len(mat[0])
8+
9+
if m*n != r*c {
10+
return mat
11+
}
12+
13+
singleRow := []int{}
14+
for _, row := range mat {
15+
singleRow = append(singleRow, row...)
16+
}
17+
18+
newMat := make([][]int, r)
19+
for i := range newMat {
20+
row := singleRow[:c]
21+
singleRow = singleRow[c:]
22+
newMat[i] = row
23+
}
24+
25+
return newMat
26+
}
27+
```
28+
29+
Solution in mind
30+
================
31+
32+
- A solution is legal only if the product of the number of rows and columns is equal to the product of required rows and columns (`m * n == r * c`).
33+
34+
- A single row (`singleRow`) is first populated to hold all the elements.
35+
36+
- A new matrix (`newMat`) is created with the required number of rows and each row is populated by removing `c` number of elements from `singleRow` and putting it into the row of the new matrix.

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ Link to profile, [bhargavsnv100](https://leetcode.com/bhargavsnv100/)
77

88
| [Easy](Easy/README.md) | [Medium](Medium/README.md) | [Hard](Hard/README.md) |
99
|------------------------|----------------------------|------------------------|
10-
| 49 | 78 | 15 |
10+
| 50 | 78 | 15 |
1111

1212
Problems finished
1313
=================
@@ -51,6 +51,7 @@ Easy
5151
- [remove-duplicates-from-sorted-array.md](Easy/remove-duplicates-from-sorted-array.md)
5252
- [remove-duplicates-from-sorted-list.md](Easy/remove-duplicates-from-sorted-list.md)
5353
- [remove-element.md](Easy/remove-element.md)
54+
- [reshape-the-matrix.md](Easy/reshape-the-matrix.md)
5455
- [reverse-integer.md](Easy/reverse-integer.md)
5556
- [reverse-linked-list.md](Easy/reverse-linked-list.md)
5657
- [roman-to-int.md](Easy/roman-to-int.md)

0 commit comments

Comments
 (0)