Ctrl K

Lining Up Against Rivals

Medium
Two teams field n players each for n one-on-one matches. The rivals are known in advance: theirs[i] is the strength of the rival in match i. Our players' strengths are in the array ours. A match goes to whoever is **strictly** stronger. The coach lines the team up using a rule that guarantees the largest possible number of wins: 1. Our players are placed one by one, from weakest to strongest. 2. If the current player is stronger than the **weakest** rival still unassigned, they take that match. 3. Otherwise they would lose anyway, so they are sent against the **strongest** rival still unassigned, saving the stronger players for winnable matches. When several free rivals are equally strong, the one with the smaller match number counts as the weakest and the one with the larger match number as the strongest. Return an array answer of length n where answer[i] is the strength of our player facing rival i.
Example 1
ours=[3, 9, 6], theirs=[5, 8, 2] → [6, 9, 3]

Go through our players from weakest to strongest. 3 beats the weakest rival, 2 (position 2). 6 beats the next weakest, 5 (position 0). 9 beats 8 (position 1). The result [6, 9, 3] wins all three matches.

Example 2
ours=[4, 4, 10], theirs=[4, 1, 7] → [10, 4, 4]

The first 4 beats the weakest rival, 1 (position 1). The second 4 does not beat the next weakest (4 against 4 is no win), so it is sent against the strongest free rival, 7 (position 2). 10 beats the remaining 4 (position 0). The answer is [10, 4, 4] with two wins.

Example 3
ours=[1, 2], theirs=[5, 5] → [2, 1]

No match can be won. 1 goes against the strongest rival; among the equal 5s the one at the larger position counts as stronger, so it is position 1. Then 2 takes the remaining position 0.

Constraints
  • 1 ≤ len(ours) ≤ 10⁵
  • len(theirs) == len(ours)
  • 0 ≤ ours[i], theirs[i] ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsStudios for Recording Sessions MediumFix the Middle of the Line MediumStick Triples That Form a Triangle MediumBest-Paid Gig for Each Worker MediumRafts for Two Medium
loading Python…
Input
ours=[3, 9, 6], theirs=[5, 8, 2]
Expected
[6, 9, 3]

Run checks the first 3 tests in your browser. Submit checks all 102 tests on the server, hidden ones included.