Skip to content

Commit 66bae81

Browse files
My solution to 2022
1 parent 0166f59 commit 66bae81

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

problems/2022/jeremymanning.md

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,44 @@
11
# [Problem 2022: Convert 1D Array Into 2D Array](https://leetcode.com/problems/convert-1d-array-into-2d-array/description/?envType=daily-question)
22

33
## Initial thoughts (stream-of-consciousness)
4+
- A nice and easy one
5+
- There are two clear approaches:
6+
- We could build up the 2D array in a for loop
7+
- Or we could use a list comprehension to build it in a single step
8+
- I'll go with the list comprehension approach, since I think we can do it as a one liner (plus a check that `m * n == len(original)`)
49

510
## Refining the problem, round 2 thoughts
11+
- Assuming the dimensions work out, I think we can just return `[original[x:(x + n)] for x in range(0, len(original), n)]`
612

713
## Attempted solution(s)
814
```python
9-
class Solution: # paste your code here!
10-
...
15+
class Solution:
16+
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
17+
if m * n == len(original):
18+
return [original[x:(x + n)] for x in range(0, len(original), n)]
19+
else:
20+
return []
1121
```
22+
- Given test cases pass
23+
- Submitting...
24+
25+
![Screenshot 2024-08-31 at 9 48 44 PM](https://github.com/user-attachments/assets/f1d0b5ee-380f-4e7e-84f0-33e67ca02af5)
26+
27+
- Solved!
28+
- Out of curiousity, what if I change the list comprehension to a generator?
29+
30+
```python
31+
class Solution:
32+
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
33+
if m * n == len(original):
34+
return (original[x:(x + n)] for x in range(0, len(original), n))
35+
else:
36+
return []
37+
```
38+
39+
![Screenshot 2024-08-31 at 9 50 35 PM](https://github.com/user-attachments/assets/e6e9819c-f3e8-4310-b491-953493db8550)
40+
41+
- Interesting; runtime is slightly worse (though maybe still within the margin of error), but memory is slightly better.
42+
43+
44+

0 commit comments

Comments
 (0)