DEV Community

Discussion on: Day 8 - Check If Two String Arrays are Equivalent

Collapse
 
mhmelshaaer profile image
Mouhammed Elshaaer • Edited

You can optimize for memory and a much better time complexity for best-case scenarios.

bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) {
    int w1Index=0, i=0, w1N = word1.size(),
        w2Index=0, j=0, w2N = word2.size();

    while(w1Index < w1N && w2Index < w2N) {
        if (word1[w1Index][i] != word2[w2Index][j]) return false;

        if(word1[w1Index].length() - 1 > i) ++i;
        else {
            ++w1Index;
            i = 0;
        }

        if(word2[w2Index].length() - 1 > j) ++j;
        else {
            ++w2Index;
            j = 0;
        }
    }

    return w1Index + w2Index == w1N + w2N;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ruarfff profile image
Ruairí O'Brien

That's cool. Thank you!

I did a python version of it to test it out:

def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
        w1, i, w1n = 0, 0, len(word1)
        w2, j, w2n = 0, 0, len(word2)

        while w1 < w1n and w2 < w2n:
            if word1[w1][i] != word2[w2][j]:
                return False
            if len(word1[w1]) - 1 > i:
                i += 1
            else:
                w1 += 1
                i = 0

            if len(word2[w2]) - 1 > j:
                j += 1
            else:
                w2 += 1
                j = 0
        return w1 + w2 == w1n + w2n
Enter fullscreen mode Exit fullscreen mode