The objective is to convert an array like a3b5c2 to aaabbbbbcc in-place.
I have a solution:
- Assuming that the array is of infinite size,
- I parse the array from the end.
- look for a number (say n)
- depending on how many digits I get, I look for the next character.
- When I get it, I move the elements from current position through end of array by
n-1positions. - Fill the open positions with the encountered character.
The complexity of this solution will be O(n^2). Is there a solution with complexity less than O(n^2)?
If you parse the array once, you can know where the last element will be by summing all the numerical values.
Parse it once and find its final size.
Once you do that, start filling it from the “end” (from where its final value will be): 2 times
c, then 5 timesb…This is a
O(n)in-place solution.EDIT:
As srbh.kmr said in comments, this won’t work if the array has a series of badly-placed characters repeated only one time. For instance, if we have the array
a1b1c1d1e7, the answer above will erase the last letters.The only number that causes issues is
1, and we can treat it inO(n):Before treating the array as explained above, eliminate those ones. Starting from the beginning, parse the array and each time a
1is found, erase it and move the remaining letters forward (not the whole remaining array, just the next characters). If several1s are found in the array, the hole between the first and second parts of the array will get bigger. For the example array above, the steps look like this:Then, apply the algorithm above. If no number is found after a character, just copy the character to its position at the end of the array: