DDSA Solutions

2022. Convert 1D Array Into 2D Array

Time: O(mn)
Space: O(mn)

Problem Overview

Convert 1D Array Into 2D Array (Medium) asks you to solve a structured algorithmic task. This is a common Array / Matrix pattern in coding interviews. Validate m*n == len; fill 2D array row by row from 1D index.

A full step-by-step explanation is being added. See the study guide for pattern-based practice.

Approach

Validate m*n == len; fill 2D array row by row from 1D index.

Related patterns: Array, Matrix, Simulation

2022.cs
C#
// Approach: Validate m*n == len; fill 2D array row by row from 1D index.
// Time: O(mn) Space: O(mn)

public class Solution
{
    public int[][] Construct2DArray(int[] original, int m, int n)
    {
        int[][] result = new int[m][];

        if ((m * n) != original.Length)
            return new int[0][];

        int k = 0;

        for (int i = 0; i < m; i++)
        {
            result[i] = new int[n];
            for (int j = 0; j < n; j++)
            {
                result[i][j] = original[k++];
            }
        }

        return result;
    }
}
Was this solution helpful?

Related Problems