Python solution with detailed explanation

  • 0


    Valid Word Square

    Two loop solution: Time O(MN) and Space O(1)

    • Use two for loops. Outer loop iterates through each word row by row. The pointer is i.
    • Inner for loop iterates from 0 to length of the row word. The pointer is j.
    • Now word[i,j] must be equal to word[j,i].
    • We are sure that word[i,j] is valid. We must also make sure we are not accessing out of bounds for word[j,i]. Therefore we have additional checks.
    class Solution(object):
        def validWordSquare(self, words):
            :type words: List[str]
            :rtype: bool
            for i in range(len(words)):
                for j in range(len(words[i])):
                    if j < len(words) and i < len(words[j]) and words[i][j] == words[j][i]:
                        return False
            return True

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.