Valid Word Square

easy array string matrix

Problem

Given a sequence of words, return whether they form a valid word square (the kth row reads the same as the kth column).

Inputwords = ["abcd","bnrt","crmy","dtye"]
Outputtrue
Row 0 = abcd; column 0 = a,b,c,d — match. Same holds for the other rows.

def valid_word_square(words):
    n = len(words)
    for r, row in enumerate(words):
        for c, ch in enumerate(row):
            if c >= n or r >= len(words[c]) or words[c][r] != ch:
                return False
        # also ensure row length doesn't claim more than column allows
        for c in range(len(row), len(words[0])):
            if c < n and r < len(words[c]):
                return False
    return True
function validWordSquare(words) {
  const n = words.length;
  for (let r = 0; r < n; r++) {
    for (let c = 0; c < words[r].length; c++) {
      if (c >= n || r >= words[c].length || words[c][r] !== words[r][c]) return false;
    }
  }
  for (let c = 0; c < n; c++) {
    for (let r = 0; r < words[c].length; r++) {
      if (r >= n || c >= words[r].length || words[c][r] !== words[r][c]) return false;
    }
  }
  return true;
}
class Solution {
    public boolean validWordSquare(List words) {
        int n = words.size();
        for (int r = 0; r < n; r++) {
            String row = words.get(r);
            for (int c = 0; c < row.length(); c++) {
                if (c >= n || r >= words.get(c).length() || words.get(c).charAt(r) != row.charAt(c)) return false;
            }
        }
        return true;
    }
}
bool validWordSquare(vector& words) {
    int n = words.size();
    for (int r = 0; r < n; r++) {
        for (int c = 0; c < (int)words[r].size(); c++) {
            if (c >= n || r >= (int)words[c].size() || words[c][r] != words[r][c]) return false;
        }
    }
    return true;
}
Time: O(n²) Space: O(1)