1768. Merge Strings Alternately ¶ Time: $O(n)$ Space: $O(n)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12 13 14class Solution { public: string mergeAlternately(string word1, string word2) { const int n = min(word1.length(), word2.length()); string prefix; for (int i = 0; i < n; ++i) { prefix += word1[i]; prefix += word2[i]; } return prefix + word1.substr(n) + word2.substr(n); } }; 1 2 3 4 5 6 7 8 9 10 11 12 13class Solution { public String mergeAlternately(String word1, String word2) { final int n = Math.min(word1.length(), word2.length()); StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; ++i) { sb.append(word1.charAt(i)); sb.append(word2.charAt(i)); } return sb.append(word1.substring(n)).append(word2.substring(n)).toString(); } } 1 2 3class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: return ''.join(a + b for a, b in zip_longest(word1, word2, fillvalue=''))