Construct 2D Grid Matching Graph Layout - Problem

Imagine you're an architect tasked with designing a floor plan where rooms must be arranged in a perfect rectangular grid, and hallways connect specific rooms as specified in your blueprint.

You're given a 2D integer array edges representing an undirected graph with n nodes, where edges[i] = [ui, vi] denotes a connection between nodes ui and vi.

Your challenge is to construct a 2D grid that satisfies these strict conditions:

  • The grid contains all nodes from 0 to n-1, with each node appearing exactly once
  • Two nodes are adjacent in the grid (horizontally or vertically) if and only if there's an edge between them
  • No diagonal connections are allowed - only up, down, left, right adjacency

The problem guarantees that such a valid 2D grid layout always exists for the given edges.

Goal: Return any valid 2D integer array representing this grid layout.

Input & Output

example_1.py โ€” 2ร—2 Grid
$ Input: edges = [[0,1],[1,3],[2,3],[0,2]]
โ€บ Output: [[0,1],[2,3]]
๐Ÿ’ก Note: This forms a 2ร—2 grid where node 0 connects to nodes 1 and 2, node 1 connects to nodes 0 and 3, node 2 connects to nodes 0 and 3, and node 3 connects to nodes 1 and 2. The adjacency perfectly matches a rectangular grid layout.
example_2.py โ€” Single Row
$ Input: edges = [[0,1],[1,2],[2,3]]
โ€บ Output: [[0,1,2,3]]
๐Ÿ’ก Note: This creates a linear path that forms a 1ร—4 grid (single row). Each node is connected only to its immediate neighbors in the sequence.
example_3.py โ€” Single Node
$ Input: edges = []
โ€บ Output: [[0]]
๐Ÿ’ก Note: With only one node and no edges, the result is a 1ร—1 grid containing just node 0.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Each node is visited exactly once during BFS traversal

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Space for adjacency list, visited set, and result grid

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค n โ‰ค 5 ร— 104
  • 0 โ‰ค edges.length โ‰ค 5 ร— 104
  • edges[i].length == 2
  • 0 โ‰ค ui, vi < n
  • ui โ‰  vi
  • The given edges can always form a valid 2D grid
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen