Valid Arrangement of Pairs — LeetCode 2097 Python Solution

HardDepth-First SearchGraphEulerian Circuit
Problem
#2097
Reading time
2 min

The problem

You are given a 0-indexed 2D integer array pairs where pairs[i] = [starti, endi]. An arrangement of pairs is valid if for every index i where 1 <= i < pairs.length, we have endi-1 == starti.

Example

Input
pairs = [[5,1],[4,5],[11,9],[9,4]]
Output
[[11,9],[9,4],[4,5],[5,1]]
Explanation
This is a valid arrangement since endi-1 always equals starti.

Complexity

MeasureComplexity
TimeO(V+E)
SpaceO(V) auxiliary

Pattern: Depth-First Search

Follow one path to its end before trying the next — the default way to explore a graph. LeetCode 2097. Valid Arrangement of Pairs is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Depth-First Search and Graph.

The depth-first search guide has the Python template for the pattern and the 366 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2097. Valid Arrangement of Pairs?
LeetCode 2097. Valid Arrangement of Pairs is rated Hard on LeetCode.
What is the time complexity of LeetCode 2097. Valid Arrangement of Pairs?
The Python solution on this page runs in O(V+E).
What is the space complexity of LeetCode 2097. Valid Arrangement of Pairs?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 2097. Valid Arrangement of Pairs cover?
LeetCode 2097. Valid Arrangement of Pairs is tagged Depth-First Search, Graph and Eulerian Circuit on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview