← Microsoft bank

Microsoft · Question 65 · Dynamic Programming

Maximal Square

Dynamic ProgrammingJavacode⏱ O(m×n)💾 O(m×n)
Product-based

Problem

Find the largest square of 1's in a binary matrix.

Approach

dp cell = 1 + min of top/left/diagonal; track the max side.

Time O(m×n)Space O(m×n)

How it works

  1. 1A '1' extends the smallest neighbouring square.
  2. 2Track the largest side; answer is its square.

Sample input / output

Input:
4 5
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Output:
1

Constraints

1 <= m, n <= 300; cells '0'/'1'.

Solution — read it, then walk it

Time O(m×n)Space O(m×n)Loops 3Branches 1Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeatyes↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static intmaximalSquare(char[][]matrix)DEFINE m = matrix.length, n= matrix[0].lengthDEFINE [][] dp = new int[m+ 1][n + 1]DEFINE max = 0for (int i = 1; i <=m; i++)for (int j = 1; j <=n; j++)if (matrix[i - 1][j -1] == '1')dp[i][j] =Math.min(Math.min(dp[i -1][j], dp[i][j - 1]), dp[…max = Math.max(max,dp[i][j])RETURN max * maxDEFINE static voidmain(String[] args)java.util.Scanner sc = newjava.util.Scanner(System.in)DEFINE m = sc.nextInt();int n = sc.nextInt()DEFINE [][] matrix = newchar[m][n]for (int i = 0; i < m;i++) matrix[i] =sc.next().toCharArray()System.out.println(maximalSquare(matrix))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/19

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits