Leetcode - 1768. Merge Strings Alternately

Question / Problem: Leetcode

Solution

class Solution {
    public String mergeAlternately(String word1, String word2) {
        int m = word1.length(), n = word2.length(), i = 0;
        StringBuilder result = new StringBuilder();

        while(i < m || i < n) {
            if (i < m) result.append(word1.charAt(i));
            if (i < n) result.append(word2.charAt(i));
            i++;
        }

        return result.toString();
    }
}

Algorithm

  1. Initialize an empty string to store the merged string

  2. Use two pointers to iterate through each character in the two strings

  3. At each iteration, append the character at the current position of the pointer to the merged string, and increment the number

  4. Return the merged string

Space Complexity - O( M + N )

Space Complexity - O( N )

Readers

If you feel this is helpful, please do leave a Like / Comment. If you feel I can improve better, please leave comments where I can improve. Any suggestions are helpful.