1768. Merge strings Alternately (Beats 96.66%)
⚙️

1768. Merge strings Alternately (Beats 96.66%)

Tags
C#
Leetcode
Computer Science
Coding
Programming
Problem solving
Published
March 29, 2024
Author
Delgersaikhan
Find my work at delgerskhn.vercel.app Contact me at delger.bayanmunkh6@gmail.com → Let’s build something 🛠️

Problem description

You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.
Return the merged string.
Example 1:
Input: word1 = "abc", word2 = "pqr" Output: "apbqcr" Explanation: The merged string will be merged as so: word1: a b c word2: p q r merged: a p b q c r
Example 2:
Input: word1 = "ab", word2 = "pqrs" Output: "apbqrs" Explanation: Notice that as word2 is longer, "rs" is appended to the end. word1: a b word2: p q r s merged: a p b q r s
Example 3:
Input: word1 = "abcd", word2 = "pq" Output: "apbqcd" Explanation: Notice that as word1 is longer, "cd" is appended to the end. word1: a b c d word2: p q merged: a p b q c d
Constraints:
  • 1 <= word1.length, word2.length <= 100
  • word1 and word2 consist of lowercase English letters.
 

Intuition

Since we are going to mix the two strings we need pointers for the strings. That seems easier than using one iterator. If one of the pointers finished iterating, we simply append the other one at the end of the output string. It’s where that first if conditions in while loop is come from. We must begin building the string from first word. Hence, the second pointer must be lower than first pointer. So, simply append the current char from word2 if pointer 2 is less than pointer 1 otherwise appending from word1 will suffice the algorithm.
Finally, don’t forget to return the output string at the end of the function body 😉.
 

Implementation

public class Solution { public string MergeAlternately(string word1, string word2) { int l1 = word1.Length; int l2 = word2.Length; int i1 = 0; int i2 = 0; string output = ""; while(i1 < l1 || i2 < l2) { if(i1 == l1 && i2 < l2) { output += word2[i2++]; continue; } if(i2 == l2 && i1 < l1) { output += word1[i1++]; continue; } if(i2 < i1) { output+=word2[i2++]; } else { output += word1[i1++]; } } return output; } }

Summary

It took some time to solve this problem as I haven’t been doing leetcode past few months. Maybe my code is lengthy, but it works fine. The breaking condition of while loop was kinda tricky that I got some index out of range errors when I put it like i1 + i2 < l1 + l2 - 2 . Thus, I used the condition above to check both iterators are finished.
I guess the reason I got 96% on runtime speed is maybe because there aren’t many submissions in C# 😅.
 

Blog Posts