While waiting for your updated post that includes your solution, I have posted mine:
Solution
A substring is deletable if all its characters will be deleted based on your requirement. This substring may have several groups of repeated characters. For example, if the string is "accccbbbdddagggde" then "cccc" and "bbb" are deletables. A deletable substring is maximal if it is not adjacent to any deletable substring.The examples earlier are not maximal deletable substring, but "ccccbbbddd" and "ggg" are maximal. An undeletable substring is a substring that will remain in the string. A maximal undeletable substring follows the same idea as maximal deletable.
Your problem is essentially to remove all maximal deletable substring in a string, and then append the resulting string with as many 0 as the removed characters. Below is a solution:
1. Let $cur = -1$ be the starting index in the array that can be overwritten. Initially, there is no index to overwrite. Let $count$ be the number of characters that will be removed.
2. Scan the array until you find the left-most maximal deletable substring $d$. Let $d_{start}$ and $d_{end}$ be the start and end index of this string, and $d_{len} = |d|$ be $d$'s length.
3. Continue the scanning to find the maximal undeletable substring $u$ adjacent to $d$. 242
Let $u_{start}$ and $u_{end}$ be its start and end indices and $u_{len} = |u|$ be $u$'s length.
4. If both $d$ and $u$ exist, do the following:
5. If $cur$ is still -1, set $cur = d_{start}$.
6. Set $count = count + d_{len}$.
7. Copy substring $u$ at position $cur$ all the way to $cur + u_{len} - 1$. This essentially moves substring $u$ to the left, overwriting $d$, entirely or partially, depending on whether $|u| \ge |d|$.
8. Move $cur$ passed the copied substring, that is let $cur = cur + u_{len}$.
9. Go back to step 2, but the scanning will start at $u_{end} + 1$.
10. If either $u$ or $d$ does not exist, write as many 0 $count$ to the array starting at position $cur$, and we are done.
Analysis
* This solution uses only $O(1)$ extra variables, hence it uses $O(1)$ extra space.
* It overwrites an index of the array once. Either at step 4, when moving an undeletable string to the left or when writing 0's at step 5.
* This solution runs in $O(n)$ time. Observe that an index is visited at most twice, once when it is considered in the search for deletable/undeletable substring and the other when it is overwritten. Finding a deletable and undeletable takes time $O(|d|)$ and $O(|u|)$ resp., while moving an undeletable takes $O(|d|)$ time. In the worst-case, all substrings in the string will be classified as is either deletable or undeletable. Since indices are written at most once, the total time of finding and moving all such substrings is $O(n)$. 743