878374. Create a spiral matrix of N*M size from given array

Medium

Create a Spiral Matrix of N*M Size from Given Array

Summary

Given an array, create a spiral matrix of size NM. The input array is one-dimensional and its elements are arranged in a specific order to form the NM matrix. The goal is to create this matrix by printing or displaying it in a spiral manner.

Detailed Explanation

The problem requires you to take a 1D array as an input, and then transform it into a 2D matrix of size N*M. The key concept involved here is manipulation of arrays and matrices.

Here's the step-by-step breakdown of the solution:

  1. Initialize variables: Set top, bottom, left, and right to 0, which will represent the boundaries of the array.
  2. While there are still elements in the array:
    • Traverse from top to bottom (or left to right) along the boundary.
    • Print or display each element as you go.
    • Update the boundaries accordingly.
  3. Repeat step 2 until all elements have been traversed.

Here's an ASCII art diagram of how the spiral matrix should look:

1, 2, 3
4, 5, 6
7, 8, 9
10, 11, 12
13, 14, 15
16, 17, 18
19, 20, 21
22, 23, 24

Time complexity: O(n*m) Space complexity: O(1)

Optimized Solutions

Java

View on GeeksforGeeks
public class SpiralMatrix {
    public static void createSpiral(int[] array) {
        int top = 0;
        int bottom = array.length - 1;
        int left = 0;
        int right = array[0].length - 1;

        while (top <= bottom && left <= right) {
            // Traverse from top to bottom
            for (int i = left; i <= right; i++) {
                System.out.print(array[top][i] + " ");
            }
            top++;

            // Traverse from left to right
            for (int i = top; i <= bottom; i++) {
                System.out.print(array[i][right] + " ");
            }
            right--;

            // Traverse from bottom up
            if (top <= bottom) {
                for (int i = right; i >= left; i--) {
                    System.out.print(array[bottom][i] + " ");
                }
                bottom--;
            }

            // Traverse from right to left
            if (left <= right) {
                for (int i = bottom; i > top; i--) {
                    System.out.print(array[i][left] + " ");
                }
                left++;
            }
        }
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.