# 422. Valid Word Square

## compare by len

T: O(n\*L), n is words list size, L is word len

S: O(1)

```java
class Solution {
    public boolean validWordSquare(List<String> words) {
        int n = words.size();
        
        for (int i = 0; i < n; i++) { // n is col len
            String word = words.get(i);
            for (int j = 0; j < word.length(); j++) {
                // j >= n, word is too long (in row length, so n can't compare with row len)
                // words.get(j).length() <= i, col len is shorter than i
                if (j >= n || 
                    words.get(j).length() <= i ||
                    word.charAt(j) != words.get(j).charAt(i)) {
                    return false;
                }
            }
        }
        return true;
    }
}
```

## filled with empty in matrix, then compare if (w\[i]\[j] != w\[j]\[i])&#x20;

T: O(n^2), n is Square side length

S: O(n^2)

```java
class Solution {
    public boolean validWordSquare(List<String> words) {
        // check entire size is legal, max word size should equal to words list size
        int len = 0;
        for (String w : words) {
            len = Math.max(w.length(), len);
        }
        if (words.size() != len) {
            return false;
        }
        
        char w[][] = new char[len][len];
        for (int i = 0; i < len; i++) {
            StringBuilder str = new StringBuilder(words.get(i));
            int spaces = len - str.length();
            
            // fill out the empty to make all words in the same length
            for (int s = 0; s < spaces; s++) { // str length will change, so cant write in loop
                str.append(" ");    
            }
            w[i] = str.toString().toCharArray();
        }
        
        // compare w(row,col) == w(col, row)
        for (int i = 0; i < len; i++) {
            for (int j = 0; j < len; j++) {
                if (w[i][j] != w[j][i]) {
                    return false;
                }
            }
        }
        return true;
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/array_problem/422.-valid-word-square.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
