Construct 2D Grid Matching Graph Layout - Problem

You are given a 2D integer array edges representing an undirected graph having n nodes, where edges[i] = [ui, vi] denotes an edge between nodes ui and vi.

Construct a 2D grid that satisfies these conditions:

  • The grid contains all nodes from 0 to n - 1 in its cells, with each node appearing exactly once.
  • Two nodes should be in adjacent grid cells (horizontally or vertically) if and only if there is an edge between them in edges.

It is guaranteed that edges can form a 2D grid that satisfies the conditions.

Return a 2D integer array satisfying the conditions above. If there are multiple solutions, return any of them.

Input & Output

Example 1 — Basic 2×2 Grid
$ Input: edges = [[0,1],[1,3],[2,3],[2,0]]
Output: [[0,1],[2,3]]
💡 Note: Nodes 0 and 3 are corners (degree 2). Starting from corner 0: build first row [0,1], then second row [2,3]. Adjacent cells match the edges: 0-1, 1-3, 3-2, 2-0.
Example 2 — Single Row
$ Input: edges = [[0,1],[1,2],[2,3]]
Output: [[0,1,2,3]]
💡 Note: This forms a single row. Nodes 0 and 3 have degree 1 (endpoints). The path connects 0→1→2→3, so the grid is one row.
Example 3 — 1×3 Grid
$ Input: edges = [[0,1],[1,2]]
Output: [[0,1,2]]
💡 Note: Three nodes in a line. Nodes 0 and 2 are endpoints (degree 1), node 1 is in the middle (degree 2).

Constraints

  • 1 ≤ edges.length ≤ 104
  • edges[i].length == 2
  • 0 ≤ ui, vi ≤ 104
  • All the edges are distinct

Visualization

Tap to expand
INPUT GRAPHALGORITHMRESULT GRIDedges = [[0,1],[1,3],[2,3],[2,0]]0123Connected nodes must be adjacent in grid1Analyze degrees2Find corner (degree=2)3Build first row4Build remaining rowsKey: Use neighbor relationshipsCorner → Edge → Interior pattern[0, 1][2, 3]2×2 grid layoutAdjacent cells = graph edgesKey Insight:Node degrees reveal grid structure - corners have 2 neighbors, use this to build systematicallyTutorialsPoint - Construct 2D Grid Matching Graph Layout | Corner-First Construction
Asked in
Google 32 Facebook 28 Amazon 24 Microsoft 18
12.4K Views
Medium Frequency
~25 min Avg. Time
485 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