LeetCode 422: Valid Word Square Solution

Master LeetCode problem 422 (Valid Word Square), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

422. Valid Word Square

Problem Explanation

Explanation

Given a list of strings, we want to determine if they form a valid word square. A valid word square is when each row and each column read the same string.

To solve this problem, we can iterate over each string in the list and compare each character with the corresponding character in the same index of the words in the columns. If the characters do not match, we return false. If we successfully iterate through all strings and characters, we return true.

  • Time complexity: O(n * m), where n is the number of strings and m is the maximum length of a string.
  • Space complexity: O(1)

Solution Code

class Solution {
    public boolean validWordSquare(List<String> words) {
        for (int i = 0; i < words.size(); i++) {
            for (int j = 0; j < words.get(i).length(); j++) {
                if (j >= words.size() || i >= words.get(j).length() || words.get(i).charAt(j) != words.get(j).charAt(i)) {
                    return false;
                }
            }
        }
        return true;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 422 (Valid Word Square)?

This page provides optimized solutions for LeetCode problem 422 (Valid Word Square) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 422 (Valid Word Square)?

The time complexity for LeetCode 422 (Valid Word Square) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 422 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 422 in Java, C++, or Python.

Back to LeetCode Solutions