I have a question which asks us to reduce the string as follows.
The input is a string having only
A,BorC. Output must be length of
the reduced stringThe string can be reduced by the following rules
If any 2 different letters are adjacent, these two letters can be
replaced by the third letter.Eg
ABA->CA->B. So final answer is 1 (length of reduced string)Eg
ABCCCCCCCThis doesn’t become
CCCCCCCC, as it can be reduced alternatively by
ABCCCCCCC->AACCCCCC->ABCCCCC->AACCCC->ABCCC->AACC->ABC->AAas here length is 2 < (length of
CCCCCCCC)
How do you go about this problem?
Thanks a lot!
To make things clear: the question states it wants the minimum length of the reduced string. So in the second example above there are 2 solutions possible, one CCCCCCCC and the other AA. So 2 is the answer as length of AA is 2 which is smaller than the length of CCCCCCCC = 8.
I’m assuming that you are looking for the length of the shortest possible string that can be obtained after reduction.
A simple solution would be to explore all possibilities in a greedy manner and hope that it does not explode exponentially. I’m gonna write Python pseudocode here because that’s easier to comprehend (at least for me ;)):
I think the basic idea is clear: you take a queue (
std::dequeshould be just fine), add your string into it, and then implement a simple breadth first search in the space of all possible reductions. During the search, you take the first element from the queue, take all possible substrings of it, execute all possible reductions, and push the reduced strings back to the queue. The entire space is explored when the queue becomes empty.