Valid Word Square

A valid word square means that the kth row and the kth column should read the same string for every k. Let’s define a strategy to check this:

Approach

  1. Check Number of Rows and Columns: Ensure that the number of rows (i.e., the length of the words list) matches the number of columns in the first row (i.e., the length of the first string words[0]). If these are not equal, the word square is not valid.
  2. Iterate Through Rows and Columns: For every row, check if the characters in that row match the characters in the corresponding column.
  3. Handle Different Lengths: In the given examples, some rows have a smaller length than others. We should take this into consideration and handle it correctly.

Code

Below is the Python code implementing the above approach:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
    def validWordSquare(self, words: List[str]) -> bool:
        # Check if the number of rows is equal to the number of columns in the first row
        if len(words) != len(words[0]):
            return False

        # Iterate through each row
        for i in range(len(words)):
            # Iterate through each character in the current row
            for j in range(len(words[i])):
                # If the current column exceeds the number of rows or the current row exceeds the number of characters in the corresponding column, return False
                if j >= len(words) or i >= len(words[j]):
                    return False
                # If the characters at the current row and column do not match, return False
                if words[i][j] != words[j][i]:
                    return False

        # If all checks pass, return True
        return True

Explanation

  • The outer loop iterates through each row, while the inner loop iterates through each character in the current row.
  • We carefully check the corresponding characters in the current row and column. If they do not match, we immediately return False.
  • If the loop completes without finding any mismatches, we return True.

Examples

  • The function will return True for ["abcd","bnrt","crmy","dtye"] and ["abcd","bnrt","crm","dt"], as they meet the criteria.
  • It will return False for ["ball","area","read","lady"] since the 3rd row and the 3rd column do not match.

The code handles the constraints, including the different lengths of strings in the array, and checks for the validity of the word square as defined in the problem statement.