LeetCode 1743: Restore the Array From Adjacent Pairs

LeetCode 1743 Solution Explanation

Explanation

To restore the original array from the given adjacent pairs, we can use a graph-based approach. We first build a graph where each element is connected to its adjacent elements. Then, we start from any arbitrary node and traverse the graph while keeping track of the order in which we visit the nodes.

LeetCode 1743 Solutions in Java, C++, Python

class Solution {
    public int[] restoreArray(int[][] adjacentPairs) {
        Map<Integer, List<Integer>> graph = new HashMap<>();
        for (int[] pair : adjacentPairs) {
            graph.computeIfAbsent(pair[0], k -> new ArrayList<>()).add(pair[1]);
            graph.computeIfAbsent(pair[1], k -> new ArrayList<>()).add(pair[0]);
        }
        
        int n = adjacentPairs.length + 1;
        int[] result = new int[n];
        for (Map.Entry<Integer, List<Integer>> entry : graph.entrySet()) {
            if (entry.getValue().size() == 1) {
                result[0] = entry.getKey();
                break;
            }
        }
        
        result[1] = graph.get(result[0]).get(0);
        for (int i = 2; i < n; i++) {
            List<Integer> neighbors = graph.get(result[i - 1]);
            result[i] = result[i - 2] == neighbors.get(0) ? neighbors.get(1) : neighbors.get(0);
        }
        
        return result;
    }
}

Interactive Code Editor for LeetCode 1743

Improve Your LeetCode 1743 Solution

Use the editor below to refine the provided solution for LeetCode 1743. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems