3668. Restore Finishing Order
SourceWeekly Contest 465 Q1DifficultyEasyRating1255
Description
You are given an integer array order of length n and an integer array friends.
ordercontains every integer from 1 tonexactly once, representing the IDs of the participants of a race in their finishing order.friendscontains the IDs of your friends in the race sorted in strictly increasing order. Each ID in friends is guaranteed to appear in theorderarray.
Return an array containing your friends' IDs in their finishing order.
Example 1:
Input: order = [3,1,2,5,4], friends = [1,3,4]
Output: [3,1,4]
Explanation:
The finishing order is [3, 1, 2, 5, 4]. Therefore, the finishing order of your friends is [3, 1, 4].
Example 2:
Input: order = [1,4,5,3,2], friends = [2,5]
Output: [5,2]
Explanation:
The finishing order is [1, 4, 5, 3, 2]. Therefore, the finishing order of your friends is [5, 2].
Constraints:
1 <= n == order.length <= 100ordercontains every integer from 1 tonexactly once1 <= friends.length <= min(8, n)1 <= friends[i] <= nfriendsis strictly increasing
Solutions
Solution 1: Custom Sorting
Thinking
\(\textit{friends}\) is a subset of \(\textit{order}\) and must be emitted in finish order. \(n\le 100\) allows a rank map and a sort.
Set \(d[x]=i\) from \(\textit{order}\), then sort \(\textit{friends}\) by \(d[x]\).
Comparisons then use finish rank rather than the numeric id.
First, we build a mapping from the order array to record the finishing position of each ID. Then, we sort the friends array based on the finishing order of these IDs in the order array.
The time complexity is \(O(n \times \log n)\), and the space complexity is \(O(n)\), where \(n\) is the length of the order array.
1 2 3 4 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 | |