2097 - Valid Arrangement of Pairs (Hard)
Problem Link
https://leetcode.com/problems/valid-arrangement-of-pairs
Problem Statement
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.
Return any valid arrangement ofpairs.
Note: The inputs will be generated such that there exists a valid arrangement of pairs.
OriginalPython3Example 1:
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.
end0 = 9 == 9 = start1
end1 = 4 == 4 = start2
end2 = 5 == 5 = start3Example 2:
Input: pairs = [[1,3],[3,2],[2,1]]
Output: [[1,3],[3,2],[2,1]]
Explanation:
This is a valid arrangement since endi-1 always equals starti.
end0 = 3 == 3 = start1
end1 = 2 == 2 = start2
The arrangements [[2,1],[1,3],[3,2]] and [[3,2],[2,1],[1,3]] are also valid.Example 3:
Input: pairs = [[1,2],[1,3],[2,1]]
Output: [[1,2],[2,1],[1,3]]
Explanation:
This is a valid arrangement since endi-1 always equals starti.
end0 = 2 == 2 = start1
end1 = 1 == 1 = start2Constraints:
1 <= pairs.length <= 1e5pairs[i].length == 20 <= starti, endi <= 1e9starti != endi- No two pairs are exactly the same.
- There exists a valid arrangement of
pairs.
Approach 1: Iterative Hierholzer's Algorithm for an Eulerian Trail
We can think of the input as a directed graph. Each number is a vertex, and each pair is an edge going from to . For example, means we can move from vertex to vertex . The goal is to order all these edges so that the destination of one edge is the starting point of the next edge.
A path that uses every edge exactly once is called an Eulerian trail. This is exactly what the problem asks us to find. A vertex can appear multiple times in the trail, but each input pair must be used only once. Since the problem guarantees that a valid arrangement exists, we do not need to check whether an Eulerian trail is possible.
First, we build , an adjacency list. Here, contains the destinations of all edges leaving . We also build , which stores the difference between the number of outgoing edges and incoming edges for each vertex. For every pair , we increase by one and decrease by one.
The value of helps us choose the correct starting vertex. Every time we enter an intermediate vertex, we must also leave it, so its incoming and outgoing edge counts must match. However, if the trail starts and ends at different vertices, the starting vertex needs one extra outgoing edge. Therefore, if a vertex has , we must start there. Otherwise, the trail forms a circuit, and we can start at the first pair's starting vertex.
We use Hierholzer's algorithm, implemented with a stack named . Initially, the stack contains only the chosen starting vertex. The stack keeps track of the current route we are exploring. While the vertex on top of the stack has an unused outgoing edge, we remove one destination from its adjacency list using and push that destination onto the stack. Removing the edge ensures that it cannot be used again.
Eventually, the vertex on top of the stack will have no unused outgoing edges. At that point, we remove it from . If the stack is still nonempty, the new top is the vertex from which we reached the removed vertex, so we append that edge to . This is the backtracking part of the algorithm: whenever we cannot continue forward, we return to an earlier vertex and check whether it has more edges to explore.
Importantly, we record edges during backtracking, not when we first traverse them. Simply recording edges as we move forward could lead us to finish at a dead end while some edges remain unused elsewhere. Recording during backtracking allows the algorithm to combine those remaining routes into one valid trail. The edges are collected in reverse order, so we return in reverse.
For example, consider . Vertex has two outgoing edges and one incoming edge, so and we start there. Because removes the last destination, the algorithm first takes . Vertex has no outgoing edges, so is added to . Back at vertex , the algorithm explores . During backtracking, it adds and then . Reversing produces , which is a valid arrangement.
The time complexity is and the space complexity is .
class Solution:
def validArrangement(self, pairs: List[List[int]]) -> List[List[int]]:
res = []
adj, deg = defaultdict(list), Counter()
for u, v in pairs:
adj[u].append(v)
deg[u] += 1
deg[v] -= 1
st = [next((u for u in deg if deg[u] == 1), pairs[0][0])]
while st:
if adj[st[-1]]: st.append(adj[st[-1]].pop())
else:
v = st.pop()
if st: res.append([st[-1], v])
return res[::-1]2091 - Removing Minimum and Maximum From Array
Minimize end deletions needed to remove both extremes by comparing removals from the left, right, or both ends.
2140 - Solving Questions With Brainpower
Maximize exam points by comparing the reward from answering each question with the best score from skipping it.