Convert an Array Into a 2D Array With Conditions — LeetCode 2610 Python Solution
- Problem
- #2610
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an integer array nums. You need to create a 2D array from nums satisfying the following conditions: The 2D array should contain only the elements of the array nums.
Example
- Input
- nums = [1,3,4,1,2,3,1]
- Output
- [[1,3,4,2],[1,3],[1]]
- Explanation
- We can create a 2D array that contains the following rows:
Python solution
class Solution:
def findMatrix(self, nums: List[int]) -> List[List[int]]:
cnt = Counter(nums)
ans = []
for x, v in cnt.items():
for i in range(v):
if len(ans) <= i:
ans.append([])
ans[i].append(x)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2610. Convert an Array Into a 2D Array With Conditions is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2610. Convert an Array Into a 2D Array With Conditions?
- LeetCode 2610. Convert an Array Into a 2D Array With Conditions is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2610. Convert an Array Into a 2D Array With Conditions?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2610. Convert an Array Into a 2D Array With Conditions?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2610. Convert an Array Into a 2D Array With Conditions cover?
- LeetCode 2610. Convert an Array Into a 2D Array With Conditions is tagged Array and Hash Table on LeetCode.