|
1 | 1 | # [Problem 2022: Convert 1D Array Into 2D Array](https://leetcode.com/problems/convert-1d-array-into-2d-array/description/?envType=daily-question)
|
2 | 2 |
|
3 | 3 | ## 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)`) |
4 | 9 |
|
5 | 10 | ## 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)]` |
6 | 12 |
|
7 | 13 | ## Attempted solution(s)
|
8 | 14 | ```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 [] |
11 | 21 | ```
|
| 22 | +- Given test cases pass |
| 23 | +- Submitting... |
| 24 | + |
| 25 | + |
| 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 | + |
| 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