KatInterview

422. Valid Word Square

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to determine if a given list of strings, words, forms a valid word square. A word square is defined by a symmetry property: for any index k, the k-th row and the k-th column must read the same string. If we visualize the words as a grid where words[i] is the i-th row, this condition means that the character at grid[i][j] must be equal to the character at grid[j][i] for all valid i and j.

Solution

Valid Word Square in Python

class Solution:
    def validWordSquare(self, words: List[str]) -> bool:
        n = len(words)
        for i in range(n):
            for j in range(len(words[i])):
                # For each character words[i][j], we check its symmetric counterpart words[j][i].

                # 1. Check if the symmetric row 'j' is within the grid bounds.
                # If j is too large, it means words[i] is longer than the number of rows,
                # so a symmetric grid is not possible.
                if j >= n:
                    return False
                
                # 2. Check if the symmetric column 'i' is within the bounds of row 'j'.
                # If row 'j' is shorter than index 'i', it's an asymmetry.
                if i >= len(words[j]):
                    return False
                
                # 3. Finally, check if the characters match.
                if words[i][j] != words[j][i]:
                    return False
        
        # If all checks pass, it's a valid word square.
        return True

Valid Word Square in Java

class Solution {
    public boolean validWordSquare(List<String> words) {
        int n = words.size();
        for (int i = 0; i < n; i++) {
            String currentWord = words.get(i);
            for (int j = 0; j < currentWord.length(); j++) {
                // For each character words.get(i).charAt(j), we check its symmetric counterpart words.get(j).charAt(i).

                // 1. Check if the symmetric row 'j' is within the grid bounds.
                // If j is too large, it means words[i] is longer than the number of rows,
                // so a symmetric grid is not possible.
                if (j >= n) {
                    return false;
                }

                // 2. Check if the symmetric column 'i' is within the bounds of row 'j'.
                // If row 'j' is shorter than index 'i', it's an asymmetry.
                if (i >= words.get(j).length()) {
                    return false;
                }

                // 3. Finally, check if the characters match.
                if (currentWord.charAt(j) != words.get(j).charAt(i)) {
                    return false;
                }
            }
        }

        // If all checks pass, it's a valid word square.
        return true;
    }
}

Valid Word Square in C++

class Solution {
public:
    bool validWordSquare(vector<string>& words) {
        int n = words.size();
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < words[i].length(); ++j) {
                // For each character words[i][j], we check its symmetric counterpart words[j][i].
                
                // 1. Check if the symmetric row 'j' is within the grid bounds.
                // If j is too large, it means words[i] is longer than the number of rows,
                // so a symmetric grid is not possible.
                if (j >= n) {
                    return false;
                }
                
                // 2. Check if the symmetric column 'i' is within the bounds of row 'j'.
                // If row 'j' is shorter than index 'i', it's an asymmetry.
                if (i >= words[j].length()) {
                    return false;
                }
                
                // 3. Finally, check if the characters match.
                if (words[i][j] != words[j][i]) {
                    return false;
                }
            }
        }
        
        // If all checks pass, it's a valid word square.
        return true;
    }
};

Valid Word Square in TypeScript

function validWordSquare(words: string[]): boolean {
    const n = words.length;
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < words[i].length; j++) {
            // For each character words[i][j], we check its symmetric counterpart words[j][i].

            // 1. Check if the symmetric row 'j' is within the grid bounds.
            // If j is too large, it means words[i] is longer than the number of rows,
            // so a symmetric grid is not possible.
            if (j >= n) {
                return false;
            }

            // 2. Check if the symmetric column 'i' is within the bounds of row 'j'.
            // If row 'j' is shorter than index 'i', it's an asymmetry.
            if (i >= words[j].length) {
                return false;
            }

            // 3. Finally, check if the characters match.
            if (words[i][j] !== words[j][i]) {
                return false;
            }
        }
    }

    // If all checks pass, it's a valid word square.
    return true;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.