Trains the technique from
LeetCode 2097Valid Arrangement of PairsThis is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.
Same function shape, different story and different numbers.
A haulage log is given as pairs, where pairs[i] is [from, to] for one run between two junctions. The two junctions on a run are never the same, and no run is logged twice.
An itinerary puts every run in some order so that each run starts where the one before it ended. At least one itinerary is guaranteed to exist.
Write an itinerary out flat, as the junctions of its first run followed by those of its second, and so on. Return the itinerary whose flat form comes first in dictionary order.
Example 1
Junction 0 has one more departure than arrival, so the itinerary has to open there, and junction 3 has one more arrival, so it closes there. Setting off on the run to junction 1 would strand the pair between 0 and 2, so the itinerary goes 0 to 2, back to 0, on to 1 and then to 3.
Example 2
Every junction balances, so the itinerary closes where it opened and may open anywhere on the loop. Opening at junction 1 gives the smallest flat form.
Example 3
A single run is already an itinerary.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def valid_arrangement(pairs: list[list[int]]) -> list[list[int]]:public int[][] validArrangement(int[][] pairs)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.