sudopower

LC: 1768: Merge Strings Alternatively

lc_1768

 

Link to problem

Solution 3

func mergeAlternately(word1 string, word2 string) string {
    /*Solution 3
        Create res variable
        Loop over shorter string
        Concat longer string
        Use string builder
    */

    var res strings.Builder
    var i int
    for i=0;i<min(len(word1),len(word2));i++{
        res.Write([]byte{word1[i],word2[i]})
    }

    if len(word1)-i>0{        
        res.WriteString(word1[i:])
    } else {
        res.WriteString(word2[i:])
    }

    return res.String()
}

Time Complexity – O(m+n)

Space Complexity – O(m+n)

func mergeAlternately(word1 string, word2 string) string { 
    resStr := ""                            // 1 time and space
    w1Len := len(word1)                     // 1 time and m space
    w2Len := len(word2)                     // 1 time and n space
    for i:=0;i<min(w1Len,w2Len);i++{        // min(m,n) time and 1 space
        resStr+=string(word1[i])            // 1 time and 1 space
        resStr+=string(word2[i])            // 1 time and 1 space
    }

    if w1Len<w2Len{                         // 1 time 
        resStr+=word2[w1Len:]               // n-m time and n-m space
    } else {
        resStr+=word1[w2Len:]               // m-n time and m-n space
    }

    return resStr                           
}

/* 
total time complexity:
1+1+1+2*min(m,n)+1+1+1+(n-m or m-n) = O(m+n)
total space complexity:
1+2*min(m,n)+1+1+1+(n-m or m-n) = O(m+n)
*/

Solution 2

func mergeAlternately(word1 string, word2 string) string {
    resStr := ""
    w1Len := len(word1)
    w2Len := len(word2)
    for i:=0;i<max(w1Len,w2Len);i++{
        if i<w1Len{
            resStr+=string(word1[i])
        }

        if i<w2Len{
            resStr+=string(word2[i])
        }
    }

    return resStr
}

Solution 1

func mergeAlternately(word1 string, word2 string) string {
    resStr := ""
    w1Len := len(word1)
    w2Len := len(word2)    
    for i:=0;i<min(w1Len,w2Len);i++{        
        resStr+=string(word1[i])
        resStr+=string(word2[i])        
    }

    if w1Len<w2Len{
        resStr+=word2[w1Len:]
    } else {
        resStr+=word1[w2Len:]
    }

    return resStr
}