#2097

Valid Arrangement of Pairs

Hard
ArrayDepth-First SearchGraph TheoryEulerian CircuitGraph TraversalDepth-First Search
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 solution treats the pairs as a directed graph where each pair represents an edge. We can use a depth-first search (DFS) to find an Eulerian path, which guarantees a valid arrangement of pairs.

⚙️

Algorithm

3 steps
  1. 1Step 1: Build a graph using a hashmap where each key is a start node and its value is a stack of end nodes.
  2. 2Step 2: Perform a depth-first search (DFS) starting from any node to traverse the graph and collect the pairs in the correct order.
  3. 3Step 3: Reverse the collected pairs to get the valid arrangement.
solution.py13 lines
1from collections import defaultdict
2
3def valid_arrangement(pairs):
4    graph = defaultdict(list)
5    for start, end in pairs:
6        graph[start].append(end)
7    result = []
8    def dfs(node):
9        while graph[node]:
10            dfs(graph[node].pop())
11        result.append(node)
12    dfs(pairs[0][0])
13    return [[result[i], result[i+1]] for i in range(len(result)-1)][::-1]

Complexity note: The time complexity is O(n) because we traverse each pair once to build the graph and again during the DFS. The space complexity is O(n) due to the storage of the graph and the result list.

  • 1Pairs can be treated as directed edges in a graph.
  • 2A valid arrangement corresponds to finding an Eulerian path.

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