2
public int[] restoreArray(int[][] adjacentPairs) {3
// Build an adjacency list graph.4
Map<Integer, Queue<Integer>> iToPairs = new HashMap<>();5
for (int[] pair : adjacentPairs) {6
iToPairs.computeIfAbsent(pair[0], k -> new ArrayDeque<>()).add(pair[1]);7
iToPairs.computeIfAbsent(pair[1], k -> new ArrayDeque<>()).add(pair[0]);10
// Find an item that has only one neighbour.12
for (int i : iToPairs.keySet()) {13
if (iToPairs.get(i).size() == 1) {19
// Traverse the graph in a linked-list fashion.20
int n = iToPairs.size();22
int[] restored = new int[n];23
restored[writeIdx++] = start;24
while (writeIdx < n) {25
int next = iToPairs.get(start).remove();26
iToPairs.remove(start);27
iToPairs.get(next).remove(start); // Remove the loop back to the current start.28
restored[writeIdx++] = next;