You are given a string S. In one move you can erase from S a pair of identical letters. Find the shortest possible string that can be created this way.
If there are many such strings, choose the alphabetically (lexicographically) smallest one.
Note that there is no limit to the number of moves.
Write a function:
given a string S of length N, returns the shortest string (or the first alphabetically, in the case of a draw) created by erasing pairs of identical letters from S.
Examples
01 Β· Example 1
S = "CBCAAXA" return = "BAX"
For the input string S, you can make, for example, two moves:
First, erase a pair of letters "C": "CBCAAXA" β "BAAXA".
Then, erase a pair of letters "A": "BAAXA" β "BAX".
Thus the string "BAX" is created. There is no way to create a shorter string. The other string of length 3 that can be created is "BXA", but "BAX" is the first alphabetically. The function should return "BAX".
02 Β· Example 2
S = "ZYXZYZY" return = "XYZ"
First, erase a pair of letters "Y": "ZYXZYZY" β "ZXZYZ".
Then, erase a pair of letters "Z": "ZXZYZ" β "XYZ".
The other strings of length 3 that can be created are "ZYX", "YXZ", "XZY" and "ZXY", but "XYZ" is alphabetically the first, so the function should return "XYZ".
03 Β· Example 3
S = "ABCBACDDAA" return = " "
For S = "ABCBACDDAA" all five pairs of identical letters can be erased. The function should return "" (empty string).
Constraints
N/A (If you know about it, feel free to contact us ;D tysm!More Amazon problems
- Closest Version DateONSITE INTERVIEW Β· Seen Jul 2026
- Maximum Concurrent Processes (Bar Raiser Round)ONSITE INTERVIEW Β· Seen Jul 2026
- Maximum Product New RatingOA Β· Seen Jul 2026
- Permutation SorterOA Β· Seen Jul 2026
- Get Distinct Pairs (Also apply to AS intern)Seen Jul 2026
- Maximum Final ValueSeen Jul 2026
- Minimum Delivery Center InconvenienceOA Β· Seen Jun 2026
- Unfulfilled Customers by Inventory PriorityOA Β· Seen Jun 2026
public String erasePairs(String s) {
// write your code here
}
S"CBCAAXA"
expected"BAX"
checking account