
Problem
Solution
Submissions
Convert a 2D Array into a 1D Array
Certification: Basic Level
Accuracy: 33.33%
Submissions: 6
Points: 5
Write a C# program to convert a 2D array into a 1D array. There are various strategies for flattening a 2D array, but for this problem, use row-major order (traverse each row from left to right, then move to the next row).
Example 1
- Input: matrix = [
[1, 2, 3],
[4, 5, 6] ] - Output: [1, 2, 3, 4, 5, 6]
- Explanation:
- Step 1: Determine the dimensions of the input 2D array (2 rows × 3 columns).
- Step 2: Calculate the total size needed for the 1D array (2 * 3 = 6).
- Step 3: Create a new 1D array with the calculated size.
- Step 4: Traverse the 2D array in row-major order and copy each element to the 1D array.
- Step 5: The 2D array has 2 rows and 3 columns. In row-major order, we first take all elements from the first row (1, 2, 3), then all elements from the second row (4, 5, 6).
Example 2
- Input: matrix = [
[9],
[8],
[7] ] - Output: [9, 8, 7]
- Explanation:
- Step 1: Determine the dimensions of the input 2D array (3 rows × 1 column).
- Step 2: Calculate the total size needed for the 1D array (3 * 1 = 3).
- Step 3: Create a new 1D array with the calculated size.
- Step 4: Traverse the 2D array in row-major order and copy each element to the 1D array.
- Step 5: The 2D array has 3 rows and 1 column. In row-major order, we take the element from each row (9, 8, 7).
Constraints
- 1 ≤ matrix.length ≤ 100
- 1 ≤ matrix[i].length ≤ 100
- 0 ≤ matrix[i][j] ≤ 10000
- Time Complexity: O(m*n)
- Space Complexity: O(m*n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Determine the total number of elements in the 2D array.
- Create a 1D array of the appropriate size.
- Use nested loops to iterate through the 2D array.
- Calculate the corresponding 1D index for each element in the 2D array.
- Handle cases where rows might have different lengths.