educative.io

Possibly wrong exit condition?

In this exercise, it might happen that some strings cannot be built with different adjacent characters.

In this case, the algorithm returns an empty string, by checking whether the variable previous is not null and the priority queue is empty.

But this condition appears inside the while loop, which has !queue.isEmpty() as a guard condition, so it’ll never reach the if-block to have that final check when we want to.

I think this check could be moved outside the while loop.

Hi @Angelo_Marchesin
For the specific input you discussed, it will reach the if block to have the final check. As the condition written in the while loop is with || (OR operator) and the condition written in the if block is with && (AND operator) so when a user gives input like "aaab" which can not be built with different adjacent characters, it will pass through while loop and if block to give resultant empty string.
For further confirmation, you can replace the empty string with some specific string to view the changes.
Happy Learning :slightly_smiling_face: