Day 2: Merge Strings Alternately – My Leetcode Journey

Brad Malgas
Author
Explored string immutability and learned why appending to strings is inefficient. Reverted to the simpler solution after testing optimizations.
Day two—what a journey it’s been. Today’s problem was 1768. Merge Strings Alternately. As usual, I timed myself and noted how long it took. This time I was able to complete the problem within 10 minutes 50 seconds. Bearing in mind that these are easy problems meant to be solved quickly, it’s important to pace yourself.
My problem-solving approach once again followed my personal 5-step plan: Write down → Solve → Code solution → Analyze → Optimize.
For this problem, I noted three things when reading it:
- Since I planned on using a single loop, the length of the shorter string would determine how long my loop should run.
- After the loop, I could append the remaining characters of the longer string to the merged result.
- This works because at that point one of the words will be empty while the other may still have characters left (or both may be empty).
Before coding, I wrote the algorithm as follows:
- Check which word is shorter and set that as the end of the loop.
- For each index
iin the loop, addword1[i]to the merged string, then addword2[i]. - After the loop, add the remaining characters from the longer word.
My first solution had a runtime of 32ms and used 17.7MB of memory. I couldn’t find any clear errors, so I turned to the AlgoMap solution video and community submissions.
Turns out I missed a crucial point. Since I was appending to a string each time, and strings are immutable, I was effectively creating a new string for every append. A better solution was to use an array and convert it into a string at the end. Credit to AlgoMap for explaining this clearly.
After applying this change, my final solution had a runtime of 42ms but memory usage dropped to 17.3MB. In this case, I felt the small memory savings didn’t outweigh the performance loss, so I reverted to my initial solution.
My solution can be found on my GitHub: 1768. Merge Strings Alternately
Loading reactions…
Loading comments…