Loading collection data...
Collections are a way for you to organize kata so that you can create your own training routines. Every collection you create is public and automatically sharable with other warriors. After you have added a few kata to a collection you and others can train on the kata contained within the collection.
Get started now by creating a new collection.
Yes, it's a trade off.
In your solution, which does not waste memory, you check the whole string twice.
Another solution would be to first create the wasteful buffer, write the solution into it, now determine the actual size.
Create a new buffer, copy the string from the wasteful buffer, free the wasteful buffer, return the new memory optimized buffer.
But hell, we are optimizing something really tiny and even if the string was quite large, then this third solution would be problematic, because temporarily you need almost twice the memory.
This comment is hidden because it contains spoiler information about the solution
array_count_values() was my first pick, too, but then I realized, that PHP only allows strings or integers as array keys. That's why this weird string conversion has to happen.