I am preparing myself for an interview that I have on monday and I found this problem to resolve called "String Reduction". The problem is stated like this :
Given a string consisting of a,b and c's, we can perform the following operation: Take any two adjacent distinct characters and replace it with the third character. For example, if 'a' and 'c' are adjacent, they can replaced with 'b'. What is the smallest string which can result by applying this operation repeatedly?
For instance, cab -> cc or cab -> bb, resulting in a string of length 2. For this one, one optimal solution is: bcab -> aab -> ac -> b. No more operations can be applied and the resultant string has length 1. If the string is = CCCCC, no operations can be performed and so the answer is 5.
I have seen a lot questions and answers on stackoverflow but I would like to verify my own algorithm. Here is my algorithm in pseudo code. In my code
- S is my string to reduce
- S[i] is the character at index i
- P is a stack:
redux is the function that reduces the characters.
function reduction(S[1..n]){ P = create_empty_stack(); for i = 1 to n do car = S[i]; while (notEmpty(P)) do head = peek(p); if( head == car) break; else { popped = pop(P); car = redux (car, popped); } done push(car) done return size(P)}
The worst-case of my algorithms is O(n) because all the operations on the stack P is on O(1). I tried this algorithm in the examples above, I get the expected answers. Let me execute my algo with this example " abacbcaa" :
i = 1 :
car = S[i] = a, P = {∅}
P is empty, P = P U {car} -> P = {a}
i = 2 :
car = S[i] = b, P = {a}
P is not empty :
head = a
head != car ->
popped = Pop(P) = a
car = reduction (car, popped) = reduction (a,b) = c
P = {∅}
push(car, P) -> P = {c}
i = 3 :
car = S[i] = a, P = {c}
P is not empty :
head = c
head != car ->
popped = Pop(P) = c
car = reduction (car, popped) = reduction (a,c) = b
P = {∅}
push(car, P) -> P = {b}
...
i = 5 : (interesting case)
car = S[i] = c, P = {c}
P is not empty :
head = c
head == car -> break
push(car, P) -> P = {c, c}
i = 6 :
car = S[i] = b, P = {c, c}
P is not empty :
head = c
head != car ->
popped = Pop(P) = c
car = reduction (car, popped) = reduction (b,c) = a
P = {c}
P is not empty : // (note in this case car = a)
head = c
head != car ->
popped = Pop(P) = c
car = reduction (car, popped) = reduction (a,c) = b
P = {∅}
push(car, P) -> P = {b}
... and it continues until n
I have run this algorithm on various examples like this, it seems to work. I have written a code in Java that test this algorithm, when I submit my code to the system, I am getting wrong answers. I have posted the java code on gisthub so you can see it.
Can someone tell me what is wrong with my algorithm.