← All solutions

Convert 1D Array Into 2D Array

May 31, 2025 • Go •array, matrix, simulation • easy

Problem

  • You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, m and n. You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original.

Reflections

It's just math

Go Solution

func construct2DArray(original []int, m int, n int) [][]int {
    if m * n != len(original) {
        return [][]int{}
    }

    res := [][]int{}
    for i := 0; i < m; i++ {
        res = append(res, original[n*i:i*n+n])
    }
    return res
}
LeetCode Problem Link