How would you like to learn today?
Visualize algorithms in real time, explore them step by step, or challenge yourself with a test.Choose a path to focusโor scroll down to preview all options.
Visualize the algorithm step-by-step with interactive animations in real time.
Read the full explanation, examples, and starter code at your own pace.
Drag and arrange the algorithm steps in the correct execution order.
๐ง Select Active to activate
Follow every state change, comparison, and transformation as the execution unfolds in real time.
๐ Select Passive to activate
Difficulty: ๐ด Hard
Topics: Dynamic Programming, Stack, Matrix
Goal: Find the largest rectangle made of only 1s in a binary matrix and return its area.
Given a binary matrix, return the area of the largest rectangle containing only 1's.
Input:
[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
Output: 6
๐ฆ The largest rectangle of 1s has area = 6.
Input: [["0"]]
Output: 0
Input: [["1"]]
Output: 1
import java.util.Stack;
public class Main {
public static void main(String[] args) {
int[][] matrix = {
{1, 0, 1, 0, 0},
{1, 0, 1, 1, 1},
{1, 1, 1, 1, 1},
{1, 0, 0, 1, 0}
};
System.out.println(maximalRectangle(matrix)); // Output: 6
}
public static int maximalRectangle(int[][] matrix) {
if (matrix.length == 0) return 0;
int cols = matrix[0].length;
int[] heights = new int[cols];
int maxArea = 0;
for (int[] row : matrix) {
// Build histogram heights
for (int j = 0; j < cols; j++) {
heights[j] = row[j] == 1 ? heights[j] + 1 : 0;
}
// Calculate max rectangle area for current histogram
maxArea = Math.max(maxArea, area(heights));
}
return maxArea;
}
// Function to calculate largest rectangle area in histogram
public static int area(int[] heights) {
Stack<Integer> stack = new Stack<>();
int maxArea = 0;
for (int i = 0; i <= heights.length; i++) {
int currentHeight = (i == heights.length) ? 0 : heights[i];
while (!stack.isEmpty() && currentHeight < heights[stack.peek()]) {
int height = heights[stack.pop()];
int width = stack.isEmpty() ? i : i - stack.peek() - 1;
maxArea = Math.max(maxArea, height * width);
}
stack.push(i);
}
return maxArea;
}
}
โ Written by Saurabh Patil โข B.Tech CSE โข Software Developer๐ฏ Select Challenge to activate
Drag and arrange the algorithm steps in the correct execution order instead of spending time typing code letter by letter.
The algorithm is divided into three logical parts. Carefully rearrange each section in the correct order to form a complete and valid solution.
Understand Below AlgorithmGreen text means the instruction is placed in the correct position.
Red text means the instruction is in the wrong position.
Instructions with the same background color indicate particular blocks start and end.
A tick mark means the instruction is correct and locked.
๐ Locked steps cannot be moved. Only unlocked steps are draggable.
๐ Enable sound for swap feedback and completion effects.