LeetCode 1895 | Largest Magic Square | Java | Medium | Matrix & Prefix Sum | CodeByTushu
Description: π Welcome Back to CodeByTushu!
In todayβs video, we solve LeetCode 1895 β Largest Magic Square using Matrix and Prefix Sum in Java.
A magic square is defined as a k x k subgrid where the sum of integers in each row, each column, and both main diagonals are completely identical. Since any single 1 x 1 cell is trivially a magic square, the minimum answer is always 1. To find the largest possible magic square efficiently, we greedily iterate over candidate side lengths k starting from min(m, n) down to 2. The very first valid size k that satisfies the magic square invariant across all rows, columns, and diagonals is guaranteed to be the maximum possible answer.
To verify each candidate k x k subgrid in O(k) time rather than O(k^2), we precalculate row and column prefix sums. For any top-left corner (r, c), any row or column segment sum is computed in O(1). We use the first row sum as our benchmark target, early-exit if any row or column differs, and finally verify both the primary and secondary diagonals. This prefix-accelerated approach provides optimal performance well within the time limits.
π₯ Problem Highlights
β Greedy search from maximum side length min(m, n) down to 2
β 2D prefix sums for O(1) row and column range sum lookups
β Single-pass validation per candidate square in O(k) time
β Guaranteed base case of size 1 handled seamlessly
β Early-exit pruning as soon as any row or column sum mismatches
β Optimal O(min(m, n) * m * n) time and O(m * n) auxiliary space complexity
β±οΈ TIMESTAMPS
00:00 Intro
01:09 Problem Understanding & Constraints
02:27 Core Observations & Mathematical Insight
03:23 Algorithmic Approach & Prefix Sum Strategy
04:40 Line-by-Line Java Code Walkthrough
06:07 Step-by-Step Test Run & Dry Run
07:22 Time Complexity Analysis
08:07 Space Complexity Analysis
08:42 Outro & Key Takeaways
π Problem Folder & Detailed Documentation:
https://github.com/CodeByTushu/CodeByTushu-LeetCode-Solutions/tree/main/solutions/January/18-January/1895-Largest-Magic-Square
β Java Solution:
https://github.com/CodeByTushu/CodeByTushu-LeetCode-Solutions/blob/main/solutions/January/18-January/1895-Largest-Magic-Square/Solution.java
π Python Solution:
https://github.com/CodeByTushu/CodeByTushu-LeetCode-Solutions/blob/main/solutions/January/18-January/1895-Largest-Magic-Square/solution.py
β‘ C++ Solution:
https://github.com/CodeByTushu/CodeByTushu-LeetCode-Solutions/blob/main/solutions/January/18-January/1895-Largest-Magic-Square/solution.cpp
π JavaScript Solution:
https://github.com/CodeByTushu/CodeByTushu-LeetCode-Solutions/blob/main/solutions/January/18-January/1895-Largest-Magic-Square/solution.js
π LeetCode Source Code
π Admin type the link
π All LeetCode Solutions
π https://codebytushu.com/Leetcode/
π± Join CodeByTushu on WhatsApp
Get coding updates, LeetCode solutions, daily questions and more.
https://whatsapp.com/channel/0029Vb8k5mCDeON2Xwlkxe40
β€οΈ Donate
π https://codebytushu.com/Leetcode/donate.php
π₯ Perfect For
LeetCode Medium Problems
Java DSA Preparation
Matrix Algorithms
2D Prefix Sums
Magic Square Verification
Time Complexity Optimization
Coding Interview Preparation
Problem Solving
π Follow CodeByTushu
βΆοΈ YouTube: https://www.youtube.com/@codebytushu
πΈ Instagram: https://instagram.com/codebytushu/
πΌ LinkedIn: https://www.linkedin.com/company/codebytushu/
π Website: https://codebytushu.com
π GitHub: https://github.com/CodeByTushu
β€οΈ Donβt Forget To
π Like | π¬ Comment | π Subscribe
π¬ Question of the Day
Why is it optimal to test candidate square sizes k in descending order from min(m, n) down to 2?
1οΈβ£ It ensures the prefix sum array requires less memory
2οΈβ£ The first valid k found is guaranteed to be the largest, allowing immediate return
3οΈβ£ Only descending order allows checking diagonals
4οΈβ£ Smaller squares cannot be magic squares
#LeetCode1895 #LeetCode #LargestMagicSquare #Java #JavaDSA #Matrix #PrefixSum #DSA #CodingInterview #ProblemSolving #LeetCodeMedium #DailyLeetCode #JavaProgramming #CodeByTushu
π Comment the answer below! π₯Β Close description
In todayβs video, we solve LeetCode 1895 β Largest Magic Square using Matrix and Prefix Sum in Java.
A magic square is defined as a k x k subgrid where the sum of integers in each row, each column, and both main diagonals are completely identical. Since any single 1 x 1 cell is trivially a magic square, the minimum answer is always 1. To find the largest possible magic square efficiently, we greedily iterate over candidate side lengths k starting from min(m, n) down to 2. The very first valid size k that satisfies the magic square invariant across all rows, columns, and diagonals is guaranteed to be the maximum possible answer.
To verify each candidate k x k subgrid in O(k) time rather than O(k^2), we precalculate row and column prefix sums. For any top-left corner (r, c), any row or column segment sum is computed in O(1). We use the first row sum as our benchmark target, early-exit if any row or column differs, and finally verify both the primary and secondary diagonals. This prefix-accelerated approach provides optimal performance well within the time limits.
π₯ Problem Highlights
β Greedy search from maximum side length min(m, n) down to 2
β 2D prefix sums for O(1) row and column range sum lookups
β Single-pass validation per candidate square in O(k) time
β Guaranteed base case of size 1 handled seamlessly
β Early-exit pruning as soon as any row or column sum mismatches
β Optimal O(min(m, n) * m * n) time and O(m * n) auxiliary space complexity
β±οΈ TIMESTAMPS
00:00 Intro
01:09 Problem Understanding & Constraints
02:27 Core Observations & Mathematical Insight
03:23 Algorithmic Approach & Prefix Sum Strategy
04:40 Line-by-Line Java Code Walkthrough
06:07 Step-by-Step Test Run & Dry Run
07:22 Time Complexity Analysis
08:07 Space Complexity Analysis
08:42 Outro & Key Takeaways
π Problem Folder & Detailed Documentation:
https://github.com/CodeByTushu/CodeByTushu-LeetCode-Solutions/tree/main/solutions/January/18-January/1895-Largest-Magic-Square
β Java Solution:
https://github.com/CodeByTushu/CodeByTushu-LeetCode-Solutions/blob/main/solutions/January/18-January/1895-Largest-Magic-Square/Solution.java
π Python Solution:
https://github.com/CodeByTushu/CodeByTushu-LeetCode-Solutions/blob/main/solutions/January/18-January/1895-Largest-Magic-Square/solution.py
β‘ C++ Solution:
https://github.com/CodeByTushu/CodeByTushu-LeetCode-Solutions/blob/main/solutions/January/18-January/1895-Largest-Magic-Square/solution.cpp
π JavaScript Solution:
https://github.com/CodeByTushu/CodeByTushu-LeetCode-Solutions/blob/main/solutions/January/18-January/1895-Largest-Magic-Square/solution.js
π LeetCode Source Code
π Admin type the link
π All LeetCode Solutions
π https://codebytushu.com/Leetcode/
π± Join CodeByTushu on WhatsApp
Get coding updates, LeetCode solutions, daily questions and more.
https://whatsapp.com/channel/0029Vb8k5mCDeON2Xwlkxe40
β€οΈ Donate
π https://codebytushu.com/Leetcode/donate.php
π₯ Perfect For
LeetCode Medium Problems
Java DSA Preparation
Matrix Algorithms
2D Prefix Sums
Magic Square Verification
Time Complexity Optimization
Coding Interview Preparation
Problem Solving
π Follow CodeByTushu
βΆοΈ YouTube: https://www.youtube.com/@codebytushu
πΈ Instagram: https://instagram.com/codebytushu/
πΌ LinkedIn: https://www.linkedin.com/company/codebytushu/
π Website: https://codebytushu.com
π GitHub: https://github.com/CodeByTushu
β€οΈ Donβt Forget To
π Like | π¬ Comment | π Subscribe
π¬ Question of the Day
Why is it optimal to test candidate square sizes k in descending order from min(m, n) down to 2?
1οΈβ£ It ensures the prefix sum array requires less memory
2οΈβ£ The first valid k found is guaranteed to be the largest, allowing immediate return
3οΈβ£ Only descending order allows checking diagonals
4οΈβ£ Smaller squares cannot be magic squares
#LeetCode1895 #LeetCode #LargestMagicSquare #Java #JavaDSA #Matrix #PrefixSum #DSA #CodingInterview #ProblemSolving #LeetCodeMedium #DailyLeetCode #JavaProgramming #CodeByTushu
π Comment the answer below! π₯Β Close description




