Generating Spiral Matrix in Java with O(n²) Complexity

🚀 Day 41 / 100 | Spiral Matrix II -Intuition: -The goal is to generate an n × n matrix filled with numbers from 1 to n^2 in spiral order. -Start from the top row, move right, then move down the right column, then move left across the bottom row, and finally move up the left column. -After completing one layer, shrink the boundaries and repeat the process until the matrix is filled. -Approach: O(n²) -Initialize an empty n × n matrix. -Maintain four boundaries: top, bottom, left, and right. -Start filling numbers from 1 to n^2. -Fill the top row from left -> right and move the top boundary down. -Fill the right column from top -> bottom and move the right boundary left. -Fill the bottom row from right ->left and move the bottom boundary up. -Fill the left column from bottom -> top and move the left boundary right. -Repeat the process until all elements are filled. -Complexity: Time Complexity: O(n²) Space Complexity: O(n²) #100DaysOfCode #Java #DSA #LeetCode #Matrix

  • text

To view or add a comment, sign in

Explore content categories