#3311

Construct 2D Grid Matching Graph Layout

Hard
ArrayHash TableGraph TheoryMatrixGraph TraversalDegree Counting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach leverages the properties of the graph, particularly the degrees of the nodes. By identifying nodes with degree 1 and 2, we can construct the grid more efficiently without generating permutations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a degree count for each node based on the edges.
  2. 2Step 2: Identify nodes with degree 1 (endpoints) and degree 2 (interior nodes).
  3. 3Step 3: Start placing the nodes in the grid from the endpoints, ensuring adjacency based on the edges.
solution.py22 lines
1from collections import defaultdict
2
3def constructGrid(n, edges):
4    degree = defaultdict(int)
5    graph = defaultdict(list)
6    for u, v in edges:
7        degree[u] += 1
8        degree[v] += 1
9        graph[u].append(v)
10        graph[v].append(u)
11    grid = [[-1] * n for _ in range((n + 1) // 2)]
12    idx = 0
13    for node in range(n):
14        if degree[node] == 1:
15            grid[idx // 2][idx % 2] = node
16            idx += 1
17            for neighbor in graph[node]:
18                if degree[neighbor] == 2:
19                    grid[idx // 2][idx % 2] = neighbor
20                    idx += 1
21    return grid
22

Complexity note: The time complexity is O(n) because we traverse the edges and nodes a limited number of times, making it efficient even for large inputs.

  • 1Understanding node degrees helps in constructing the grid efficiently.
  • 2Identifying endpoints and interior nodes is crucial for adjacency.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.