LeetCode 1743: Restore the Array From Adjacent Pairs Solution

Master LeetCode problem 1743 (Restore the Array From Adjacent Pairs), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1743. Restore the Array From Adjacent Pairs

Problem 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.

Solution Code

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;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1743 (Restore the Array From Adjacent Pairs)?

This page provides optimized solutions for LeetCode problem 1743 (Restore the Array From Adjacent Pairs) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1743 (Restore the Array From Adjacent Pairs)?

The time complexity for LeetCode 1743 (Restore the Array From Adjacent Pairs) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1743 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1743 in Java, C++, or Python.

Back to LeetCode Solutions