Card Game
InterviewTime limit1sMemory limit512 MB
Given Bob's row of digits and Alice's digits, find the largest number Alice can form (using at least one card) that is smaller than both readings of Bob's row.
- Level
Medium6 of 10
- Topics
- Brute force, Greedy, Sorting, Implementation
- Solved
- No attempts yet
Problem
Alice and Bob each have cards, and every card has a single digit from to . Each player can form a number of up to digits using their own cards, and whoever forms the larger number wins.
Bob is too young to know how to form a large number. Instead, he lays his cards out in a row from left to right, then picks either the number formed by reading left to right or the number formed by reading right to left. For example, if the order Bob lays out on the table is , Bob can form by reading left to right, or by reading right to left.
Alice wants her younger brother Bob to win, so she plays by the following rules:
- First, she waits for Bob to lay his cards on the table.
- Whether Bob forms his number by reading left to right or right to left, Alice wants the number Bob forms to be larger than hers so her brother wins. She must use at least one card.
- Among the ways to let Bob win, she wants to form the largest number she can.
For example, suppose Bob lays his cards in the order and Alice's cards are .
- Alice can form six three-digit numbers: , , , , , .
- Since she does not know whether Bob will form or , if Alice forms , Bob wins no matter which number he forms, and this is the largest number Alice can form.
As another example, suppose Bob has and Alice has .
- The numbers Bob can form are the same in both directions: .
- The three-digit number Alice can form is , which is larger than , so Alice cannot let Bob win while using all three cards.
- Among the two-digit numbers Alice can form is , and this is the answer for this example.
Given and the values on the two players' cards as input, find the largest number Alice can form.
Input
The first line gives the number of test cases . Each test case spans three lines.
The first line gives .
The second line gives the digits on Bob's cards without spaces. Bob lays his cards on the table in this order.
The third line gives the digits on Alice's cards without spaces.
Output
Print the answer for each test case on its own line.