Valid Word Square - Problem

Given an array of strings words, return true if it forms a valid word square.

A sequence of strings forms a valid word square if the kth row and column read the same string, where 0 <= k < max(numRows, numColumns).

In other words, for each position (i, j), the character at words[i][j] should equal the character at words[j][i] (if both positions exist).

Input & Output

Example 1 — Valid Word Square
$ Input: words = ["abcd","bnrt","crmy","dtye"]
Output: true
💡 Note: Row 0: "abcd" matches Column 0: "abcd", Row 1: "bnrt" matches Column 1: "bnrt", etc. All rows equal their corresponding columns.
Example 2 — Invalid Word Square
$ Input: words = ["abcd","bnrt","crm","dt"]
Output: false
💡 Note: Row 2 is "crm" but Column 2 would be "mrd" (reading vertically). They don't match, so it's not a valid word square.
Example 3 — Single Word
$ Input: words = ["a"]
Output: true
💡 Note: Single character forms a valid 1×1 word square where row 0 equals column 0.

Constraints

  • 1 ≤ words.length ≤ 500
  • 1 ≤ words[i].length ≤ 500
  • words[i] consists of lowercase English letters

Visualization

Tap to expand
Valid Word Square INPUT words array as grid: 0 1 2 3 0 1 2 3 a b c d b n r t c r m y d t y e words = [ "abcd", "bnrt", "crmy", "dtye"] Teal cells show symmetric pairs words[i][j] == words[j][i] ALGORITHM STEPS 1 Iterate Grid Loop i from 0 to n-1 Loop j from 0 to len(words[i]) 2 Bounds Check Check if j < len(words) Check if i < len(words[j]) 3 Compare Chars Check words[i][j]==words[j][i] If not equal: return false 4 Return Result All checks passed: return true Example: i=0, j=1 words[0][1] = 'b' words[1][0] = 'b' 'b' == 'b' : OK FINAL RESULT Symmetric Property Verified: Green = diagonal (i==j) Red = symmetric pairs checked Output: true Valid Word Square All pairs (i,j) satisfy: words[i][j] == words[j][i] Key Insight: A word square has mirror symmetry along its main diagonal. For the kth row and column to read the same string, every character at position (i,j) must equal the character at position (j,i). Single pass O(n*m) where n=rows, m=max cols. Only need to check upper triangle due to symmetry. TutorialsPoint - Valid Word Square | Optimized Single Pass Approach
Asked in
Google 25 Facebook 18
15.6K Views
Medium Frequency
~15 min Avg. Time
428 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen