Covert 1D Array Into 2D Array - Leetcode 2022 - Python

NeetCodeIO · Intermediate ·⚡ Algorithms & Data Structures ·1y ago

Key Takeaways

The video demonstrates how to convert a 1D array into a 2D array using Python, with a focus on solving the LeetCode problem. The solution involves checking if the length of the input array can be rearranged into a rectangle of given dimensions, and then using a loop to build the 2D array row by row.

Full Transcript

hey everyone welcome back and let's write some more neat code today so today I'll solve the problem convert 1D array into 2D array so it's pretty much the opposite of flattening a multi-dimensional array so a picture is definitely worth a th words here so the idea is that we're given a one-dimensional array it could be of any sort of length so let's call that a length x we want to break it into a rectangle it has to be a rectangle like we can't have a piece of it missing like you know something like this like we can't have this guy missing so it has to be a rectangle and the dimensions of that rectangle are going to be M by n where these are actually parameters that are given to us so we have to take this rearrange all the elements so that they look like this where the first two elements go in the first row the second two elements go in the second row now imagine if we had five elements it's not really possible then to form a rectangle especially with these Dimensions so what we do well in that case we return an empty array as like the default value if we can form the rectangle then we form it and then we return that so those are the two choices that are given to us now you kind of just tell me by looking at it is there a quick rule of thumb or quick formula you could use to determine if x elements can fit inside a grid that looks like this well literally just check if x which remember that's the length of the input is equal to n * m if this is not the case then we return that empty array that we were talking about the default value otherwise we actually form the rectangle cuz if this is not like true if this is actually equal then it must be possible to break it up into rows and columns because these are factors of that number anyways I won't get into the math of that but how exactly do we do it well let's kind of pay attention to the variables we're actually going to be needing so we're going to mainly be needing n and M the length of this doesn't really matter because we've already confirmed this can be rearranged into a rectangle of these Dimensions so what we do is we're going to go row by row I think it makes sense to build this thing row by row so how do we know what's the first row well we start at index zero and we go up until the length of a particular row M tells us the number of rows that we have n tells us the number of columns which tells us the length of an actual row so we're going to go from 0 to nus1 that's the first row and then the next row is going to start at n so this is the second row the third row is going to start at 2 * n the fourth row is going to start at 3 * n etc etc we're just going to keep multiplying that to tell us the beginning of the row so that's easy right now we know the beginning of every single row that's going to go here first it's zero then it's going to be n then it's going to be 2 N then it's going to be 3 n etc etc this tells us the beginning right this tells us the start if I have the start how do I get the end well I know the length of a row is going to be n so the end of this row should be 3 * n + N - 1 so this is the part that we added N - one so this is the beginning Index this is the ending index if this one is actually being included in Python it would not be included so we'd get rid of the minus one but anyways that's the main idea of solving this problem the rest will probably make more sense in the code so I'm going to start with that if statement I was talking about let's just get the length of the original which is a list provided to us if that is not equal to M * n then we can return immediately otherwise we're going to build the 2D array and then finally return it and we can do that like this row by row so I'm going to say for I could say I or r i guess I'll do R just cuz it's a bit more descriptive but this tells us the current row that we're in for R in range M I guess this is something I didn't talk about in the drawing but how many rows do we have well that's this many M rows n tells us this length of a row M tells us how many rows we have so we're going to build this row by row so how do we get the current portion of the array well remember we were thinking of it in terms of pointers the start index and the end index the start is pretty simple it's always going to be n times the current row that we're at that's going to be R time n so if we're in the first row this is going to be zero if we're in the second row this is going to be n then it's going to be 2 N Etc end is going to be pretty easy to calculate after we have start it's just this plus n minus one but I'm actually not going to have this minus one because in Python we can actually do this we can take the original list and get a slice of it from the start index to the end index but it doesn't necessarily include this and for that reason we get rid of the minus one here and then this slice this tells us the row that we want to add to the result so let's just do this that's it let's run this you can see it works and it's pretty efficient I think in terms of Big O time complexity it is going to be the dimensions of the input n * m I'm assuming that those are the dimensions of this it may not necessarily be I'm reusing these from here you can imagine that these are different I guess but a space that's actually interesting we probably could have optimized the space a bit more we didn't need to necessarily take a slice in here we could have had another nested Loop that would go something like this um I don't know for I in range from the start to the end and then appended each individual element to the result if you want to you can do that I'll leave that as an exercise for the reader I encourage you to try that out but I'm not going to do that just because in a real interview I could do that in 2 seconds we all know how to do that but I prefer this solution I don't think the extra space that is is Created from a slice is really going to matter so I'm fine with this so space complexity though of this current solution if we're not counting the result it's going to be the length of one of these rows which we established is n so let's say the space complexity is n if you found this helpful check out n code. for a lot more thanks for watching and I'll see you soon

Original Description

🚀 https://neetcode.io/ - A better way to prepare for Coding Interviews 🧑‍💼 LinkedIn: https://www.linkedin.com/in/navdeep-singh-3aaa14161/ 🐦 Twitter: https://twitter.com/neetcode1 ⭐ BLIND-75 PLAYLIST: https://www.youtube.com/watch?v=KLlXCFG5TnA&list=PLot-Xpze53ldVwtstag2TL4HQhAnC8ATf Problem Link:https://leetcode.com/problems/convert-1d-array-into-2d-array/description/ 0:00 - Read the problem 0:30 - Drawing Explanation 3:38 - Coding Explanation leetcode 2022 #neetcode #leetcode #python
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from NeetCodeIO · NeetCodeIO · 0 of 60

← Previous Next →
1 Leetcode 149 - Maximum Points on a Line - Python
Leetcode 149 - Maximum Points on a Line - Python
NeetCodeIO
2 Design Linked List - Leetcode 707 - Python
Design Linked List - Leetcode 707 - Python
NeetCodeIO
3 Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
NeetCodeIO
4 Design Browser History - Leetcode 1472 - Python
Design Browser History - Leetcode 1472 - Python
NeetCodeIO
5 Number of Good Paths - Leetcode 2421 - Python
Number of Good Paths - Leetcode 2421 - Python
NeetCodeIO
6 Flip String to Monotone Increasing - Leetcode 926 - Python
Flip String to Monotone Increasing - Leetcode 926 - Python
NeetCodeIO
7 Maximum Sum Circular Subarray - Leetcode 918 - Python
Maximum Sum Circular Subarray - Leetcode 918 - Python
NeetCodeIO
8 Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
NeetCodeIO
9 Concatenated Words - Leetcode 472 - Python
Concatenated Words - Leetcode 472 - Python
NeetCodeIO
10 Data Stream as Disjoint Intervals - Leetcode 352 - Python
Data Stream as Disjoint Intervals - Leetcode 352 - Python
NeetCodeIO
11 LFU Cache - Leetcode 460 - Python
LFU Cache - Leetcode 460 - Python
NeetCodeIO
12 N-th Tribonacci Number - Leetcode 1137
N-th Tribonacci Number - Leetcode 1137
NeetCodeIO
13 Best Team with no Conflicts - Leetcode 1626 - Python
Best Team with no Conflicts - Leetcode 1626 - Python
NeetCodeIO
14 Greatest Common Divisor of Strings - Leetcode 1071 - Python
Greatest Common Divisor of Strings - Leetcode 1071 - Python
NeetCodeIO
15 Shortest Path in a Binary Matrix - Leetcode 1091 - Python
Shortest Path in a Binary Matrix - Leetcode 1091 - Python
NeetCodeIO
16 Insert into a Binary Search Tree - Leetcode 701 - Python
Insert into a Binary Search Tree - Leetcode 701 - Python
NeetCodeIO
17 Delete Node in a BST - Leetcode 450 - Python
Delete Node in a BST - Leetcode 450 - Python
NeetCodeIO
18 Shuffle the Array (Constant Space) - Leetcode 1470 - Python
Shuffle the Array (Constant Space) - Leetcode 1470 - Python
NeetCodeIO
19 Fruits into Basket - Leetcode 904 - Python
Fruits into Basket - Leetcode 904 - Python
NeetCodeIO
20 Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
NeetCodeIO
21 Naming a Company - Leetcode 2306 - Python
Naming a Company - Leetcode 2306 - Python
NeetCodeIO
22 As Far from Land as Possible - Leetcode 1162 - Python
As Far from Land as Possible - Leetcode 1162 - Python
NeetCodeIO
23 Shortest Path with Alternating Colors - Leetcode 1129 - Python
Shortest Path with Alternating Colors - Leetcode 1129 - Python
NeetCodeIO
24 Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
NeetCodeIO
25 Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
NeetCodeIO
26 Contains Duplicate II - Leetcode 219 - Python
Contains Duplicate II - Leetcode 219 - Python
NeetCodeIO
27 Path with Maximum Probability - Leetcode 1514 - Python
Path with Maximum Probability - Leetcode 1514 - Python
NeetCodeIO
28 Add to Array-Form of Integer - Leetcode 989 - Python
Add to Array-Form of Integer - Leetcode 989 - Python
NeetCodeIO
29 Unique Paths II - Leetcode 63 - Python
Unique Paths II - Leetcode 63 - Python
NeetCodeIO
30 Minimum Distance between BST Nodes - Leetcode 783 - Python
Minimum Distance between BST Nodes - Leetcode 783 - Python
NeetCodeIO
31 Design Hashmap - Leetcode 706 - Python
Design Hashmap - Leetcode 706 - Python
NeetCodeIO
32 Range Sum Query Immutable - Leetcode 303 - Python
Range Sum Query Immutable - Leetcode 303 - Python
NeetCodeIO
33 Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
NeetCodeIO
34 Middle of the Linked List - Leetcode 876 - Python
Middle of the Linked List - Leetcode 876 - Python
NeetCodeIO
35 Course Schedule IV - Leetcode 1462 - Python
Course Schedule IV - Leetcode 1462 - Python
NeetCodeIO
36 Single Element in a Sorted Array - Leetcode 540 - Python
Single Element in a Sorted Array - Leetcode 540 - Python
NeetCodeIO
37 Capacity to Ship Packages - Leetcode 1011 - Python
Capacity to Ship Packages - Leetcode 1011 - Python
NeetCodeIO
38 IPO - Leetcode 502 - Python
IPO - Leetcode 502 - Python
NeetCodeIO
39 Minimize Deviation in Array - Leetcode 1675 - Python
Minimize Deviation in Array - Leetcode 1675 - Python
NeetCodeIO
40 Longest Turbulent Array - Leetcode 978 - Python
Longest Turbulent Array - Leetcode 978 - Python
NeetCodeIO
41 Last Stone Weight II - Leetcode 1049 - Python
Last Stone Weight II - Leetcode 1049 - Python
NeetCodeIO
42 Construct Quad Tree - Leetcode 427 - Python
Construct Quad Tree - Leetcode 427 - Python
NeetCodeIO
43 Find Duplicate Subtrees - Leetcode 652 - Python
Find Duplicate Subtrees - Leetcode 652 - Python
NeetCodeIO
44 Sort an Array - Leetcode 912 - Python
Sort an Array - Leetcode 912 - Python
NeetCodeIO
45 Ones and Zeroes - Leetcode 474 - Python
Ones and Zeroes - Leetcode 474 - Python
NeetCodeIO
46 Remove Duplicates from Sorted Array II - Leetcode 80 - Python
Remove Duplicates from Sorted Array II - Leetcode 80 - Python
NeetCodeIO
47 Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
NeetCodeIO
48 Concatenation of Array - Leetcode 1929 - Python
Concatenation of Array - Leetcode 1929 - Python
NeetCodeIO
49 Symmetric Tree - Leetcode 101 - Python
Symmetric Tree - Leetcode 101 - Python
NeetCodeIO
50 Check Completeness of a Binary Tree - Leetcode 958 - Python
Check Completeness of a Binary Tree - Leetcode 958 - Python
NeetCodeIO
51 Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
NeetCodeIO
52 Find Peak Element - Leetcode 162 - Python
Find Peak Element - Leetcode 162 - Python
NeetCodeIO
53 Accounts Merge - Leetcode 721 - Python
Accounts Merge - Leetcode 721 - Python
NeetCodeIO
54 Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
NeetCodeIO
55 Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
NeetCodeIO
56 Number of Zero-Filled Subarrays - Leetcode 2348 - Python
Number of Zero-Filled Subarrays - Leetcode 2348 - Python
NeetCodeIO
57 Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
NeetCodeIO
58 Sqrt(x) - Leetcode 69 - Python
Sqrt(x) - Leetcode 69 - Python
NeetCodeIO
59 Successful Pairs of Spells and Potions - Leetcode 2300 - Python
Successful Pairs of Spells and Potions - Leetcode 2300 - Python
NeetCodeIO
60 Optimal Partition of String - Leetcode 2405 - Python
Optimal Partition of String - Leetcode 2405 - Python
NeetCodeIO

This video teaches how to convert a 1D array into a 2D array using Python, with a focus on solving the LeetCode problem. The solution involves checking if the length of the input array can be rearranged into a rectangle of given dimensions, and then using a loop to build the 2D array row by row.

Key Takeaways
  1. Check if the length of the input array can be rearranged into a rectangle of given dimensions
  2. Use a loop to build the 2D array row by row
  3. Use slicing to extract rows from the input array
💡 The key insight is to check if the length of the input array can be rearranged into a rectangle of given dimensions, and then use a loop to build the 2D array row by row.

Related Reads

📰
Traversal, Linear Search, Swapping, Shifting & More (Leetcode Code example)
Learn array operations in Java and Scala through Leetcode code examples, enhancing your problem-solving skills
Medium · Data Science
📰
The Rain Knows the Shortest Path
Learn how the natural phenomenon of raindrops on a pond illustrates the concept of breadth-first search algorithm, making it easier to understand and visualize.
Medium · Programming
📰
Data Structures & Algorithms for Mobile App Developers
Learn essential data structures and algorithms for mobile app development to improve performance and efficiency
Medium · Programming
📰
Data Structures and Algorithms Deep‑Dive — Real-world Applications of Hash Tables (Chapter 3…
Learn how hash tables are used in real-world applications and improve your coding skills with practical examples
Medium · Programming

Chapters (3)

Read the problem
0:30 Drawing Explanation
3:38 Coding Explanation
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →