Problem
You are given a string s
.
Consider performing the following operation until s
becomes empty :
- For every alphabet character from
'a'
to'z'
, remove the first occurrence of that character ins
(if it exists).
For example, let initially s = "aabcbbca"
. We do the following operations:
- Remove the underlined characters
s = "_**a**_ a** _bc_** bbca"
. The resulting string iss = "abbca"
. - Remove the underlined characters
s = "_**ab**_ b _**c**_ a"
. The resulting string iss = "ba"
. - Remove the underlined characters
s = "_**ba**_ "
. The resulting string iss = ""
.
Return the value of the strings
rightbefore applying the last operation. In the example above, answer is "ba"
.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= s.length <= 5 * 10^5
s
consists only of lowercase English letters.
Solution
Method 1 – Simulation with Last Occurrence Tracking
Intuition
The key idea is to simulate the process: in each round, remove the first occurrence of every character from ‘a’ to ‘z’. The string just before the last operation is the set of characters that will be removed in the final round. These are the characters that appear last in the string (i.e., their last occurrence). By collecting the characters at their last occurrence positions in order, we can construct the answer efficiently.
Approach
- Traverse the string and record the last index of each character.
- Iterate through the string again, and for each character, if its index matches its last occurrence, add it to the answer.
- Concatenate these characters in their original order to form the result.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(N)
, whereN
is the length of the string. - 🧺 Space complexity:
O(1)
(since there are only 26 lowercase letters).