Counting 3x3 Magic Squares in a Grid

📅 Day 53 of #100DaysOfLeetCode Problem: 840. Magic Squares In Grid Difficulty: Medium 🔍 Problem Insight A 3×3 magic square must: Contain distinct numbers from 1 to 9 Have the same sum for all rows, columns, and both diagonals The task is to count how many such 3×3 subgrids exist inside a given grid. 💡 Key Observations Magic squares are strictly limited to 3×3 Any number outside 1–9 immediately invalidates the square Duplicate values break the magic condition Grid size is small, allowing safe sliding-window checks ⚙️ Approach Slide a 3×3 window across the grid For each window: Use a HashSet to ensure values are unique and within 1–9 Compute the target sum from the first row Validate: All rows All columns Both diagonals Count all valid magic squares ⏱️ Complexity Time: O(m × n) Space: O(1) #LeetCode #Java #ProblemSolving #CodingChallenge #100DaysOfCode #DSA #LearningEveryday

  • text

To view or add a comment, sign in

Explore content categories