Magicsheet logo

Valid Word Square

Easy
25%
Updated 8/1/2025

Asked by 2 Companies

Valid Word Square

What is this problem about?

The "Valid Word Square" interview question asks you to verify if a given sequence of strings forms a valid word square. A word square is a square matrix where the k-th row and the k-th column are identical. For example, if the first row is "BALL", the first column must also be "B", "A", "L", "L".

Why is this asked in interviews?

Google and Apple use the "Valid Word Square" coding problem to test a candidate's familiarity with 2D array structures and matrix symmetry. It challenges you to handle "jagged" arrays (where rows might have different lengths) while maintaining clear and concise logic.

Algorithmic pattern used

The core pattern is the "Matrix interview pattern." You iterate through each character in the matrix using nested loops. For each character at position (r, c), you must check if it is equal to the character at (c, r). The trick is handling cases where the column or row index might be out of bounds due to unequal string lengths.

Example explanation

Words: ["ABC", "BNP", "CPQ"]

  1. Row 0: "ABC". Check Col 0: Word 0[0]='A', Word 1[0]='B', Word 2[0]='C'. Matches!
  2. Row 1: "BNP". Check Col 1: Word 0[1]='B', Word 1[1]='N', Word 2[1]='P'. Matches!
  3. Row 2: "CPQ". Check Col 2: Word 0[2]='C', Word 1[2]='P', Word 2[2]='Q'. Matches!
  4. Result: Valid Word Square.

Common mistakes candidates make

A common mistake is assuming all strings in the list have the same length. If the first word is length 4, but there are only 3 words total, it cannot be a valid square. Another error is failing to check bounds before accessing words[c][r], which will cause a crash if a row is shorter than the column index we are checking against.

Interview preparation tip

When solving the "Valid Word Square" coding problem, treat it as a symmetry check. Before you compare words[r][c] and words[c][r], always verify that c < words.length and r < words[c].length. This defensive programming prevents runtime errors and shows the interviewer you consider all edge cases.

Similar Questions