Lexicographically smallest string formed by removing duplicates
Input: S = “yzxyz”
Explanation: Removing the duplicate characters at indices 0 and 1 in the given string, the remaining string “xyz” consists only of unique alphabets only and is the smallest possible string in lexicographical order.
Input: S = “acbc”
Explanation: Removing the duplicate characters at index 3 in the given string, the remaining string “abc” consists only of unique alphabets only and is the smallest possible string in lexicographical order.
Approach: Follow the steps below to solve the problem:
- Initialize a string res to store the resultant string.
- Store the frequency of each character present in the given string in an array freq.
- Maintain an array vis for marking the characters that are already present in the resultant string res.
- Traverse the given string S and for each character S[i], perform the following:
- Decrease the frequency of the current character by 1.
- If the current character is not marked visited in the array vis, then perform the following:
- If the last letter of res is less than S[i], add S[i] to res.
- If the last letter of res is greater than S[i] and the count of the last letter of res exceeds 0, then remove that character and mark visit[S[i]] as 0 and continue this step till the above condition is satisfied.
- After breaking out from the above condition, add S[i] to res and mark visit[S[i]] as 1.
- After completing the above steps, print the string res as the result.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1) (as we are using visited and cnt both array of fixed size 26)