Merge Strings Alternately

easy string two pointers

Problem

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.

Inputa = "moon", b = "sky"
Output"mskoyon"
Pairs: (m, s), (o, k), (o, y); the trailing "n" of "moon" is appended.

def merge_alternately(a, b):
    i = j = 0
    out = []
    while i < len(a) or j < len(b):
        if i < len(a):
            out.append(a[i]); i += 1
        if j < len(b):
            out.append(b[j]); j += 1
    return "".join(out)
function mergeAlternately(a, b) {
  let i = 0, j = 0;
  let out = "";
  while (i < a.length || j < b.length) {
    if (i < a.length) out += a[i++];
    if (j < b.length) out += b[j++];
  }
  return out;
}
class Solution {
    public String mergeAlternately(String a, String b) {
        int i = 0, j = 0;
        StringBuilder out = new StringBuilder();
        while (i < a.length() || j < b.length()) {
            if (i < a.length()) out.append(a.charAt(i++));
            if (j < b.length()) out.append(b.charAt(j++));
        }
        return out.toString();
    }
}
string mergeAlternately(string a, string b) {
    int i = 0, j = 0;
    string out = "";
    while (i < (int)a.size() || j < (int)b.size()) {
        if (i < (int)a.size()) out += a[i++];
        if (j < (int)b.size()) out += b[j++];
    }
    return out;
}
Time: O(n + m) Space: O(n + m)