Leetcode Problem 1743. Restore the Array From Adjacent Pairs

1743. Restore the Array From Adjacent Pairs

Leetcode Solutions

Iterative Approach to Reconstruct the Array

  1. Create a hash map (graph) to represent the adjacency list of the graph.
  2. Populate the graph with the given adjacentPairs, where each key is a node and the value is a list of its neighbors.
  3. Find a starting node (root) which has only one neighbor, indicating it is an end of the chain.
  4. Initialize the result array (ans) with the root.
  5. Use two pointers, prev (set to a value not in the graph) and curr (set to root), to traverse the graph.
  6. While the length of ans is less than the number of unique elements: a. For each neighbor of curr, if the neighbor is not prev, add it to ans, update prev to curr, and curr to the neighbor. b. Break the inner loop to move to the next node.
  7. Return the result array ans.
UML Thumbnail

Depth-First Search (DFS) to Reconstruct the Array

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...