Problem 3
Course: Intro Class - DSA - chapter 7
Q - You are given a string containing lower-case english alphabets. You need to perform the following operation as many times as possible:
Take the first occurrence of each alphabet if it exists and remove it from the string. Eventually the string becomes empty.
For example, let’s say the string is “ababcba”.
In the first move, we need to remove the first occurrence of each character ‘a’, ‘b’ and ‘c’. It becomes
“ababcba” → “abba”
Again, we repeat unless the string becomes empty
“abba” → “ba”
“ba” → “”
Find the last non-empty value for the string.
Example 1:
Input: s = "ababcba"Output: "ba"Explanation: ababcba -> abba -> ba -> “”Solution
Section titled “Solution”**Brute force**
We can do the moves iteratively, till we reach empty string. Also, before we do a move we need to maintain the last string value as well. Once we reach empty string, the ans is the last string value.
// Pseudo codefunction make_move(s) { // remove first occurence of each character of s and return resultant string}
last_val = ""while (s is not empty) { last_val = s s = make_move(s)}**Optimisation**
💡 Whenever there is some moves involved, generally there is some pattern that is followed that can help us quickly determine the final state
Let’s answer these 2 questions:
- What will be the final set of characters?
- Which occurrence of these final set of characters are remaining? Focus on this: We are removing one character of each type in every move. What will be left? Obviously, the characters with maximum frequency. We can quickly determine that running 2 loops right? One for frequency and one for getting the characters with max frequency.
Now for 2, focus on this: Take the **first occurrence. **So essentially what will be pending is the last occurrence of these characters right?
So final answer will be, the last occurrence of the maximum occurring characters.
Now we have everything, but can we write a cleaner code? Yes. What is the last occurrence of a character? It is the first occurrence in reverse right? Now you want to generate a string containing only **last occurrences **of **some **characters. How to go about it? Take the first occurrence in reverse order. But the final string is reversed as we travelled in reverse order. So the answer will be reverse of derived string.