Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
A farmer has a rectangular grid of land with m rows and n columns that can be divided into unit cells. Each cell is either fertile (represented by a 1) or barren (represented by a 0). All cells outside the grid are considered barren.
A pyramidal plot of land can be defined as a set of cells with the following criteria:
1 and all cells must be fertile.(r, c) be the apex of the pyramid, and its height be h. Then, the plot comprises of cells (i, j) where r <= i <= r + h - 1 and c - (i - r) <= j <= c + (i - r).An inverse pyramidal plot of land can be defined as a set of cells with similar criteria:
1 and all cells must be fertile.(r, c) be the apex of the pyramid, and its height be h. Then, the plot comprises of cells (i, j) where r - h + 1 <= i <= r and c - (r - i) <= j <= c + (r - i).Some examples of valid and invalid pyramidal (and inverse pyramidal) plots are shown below. Black cells indicate fertile cells.
Given a 0-indexed m x n binary matrix grid representing the farmland, return the total number of pyramidal and inverse pyramidal plots that can be found in grid.
Example 1:
Input: grid = [[0,1,1,0],[1,1,1,1]] Output: 2 Explanation: The 2 possible pyramidal plots are shown in blue and red respectively. There are no inverse pyramidal plots in this grid. Hence total number of pyramidal and inverse pyramidal plots is 2 + 0 = 2.
Example 2:
Input: grid = [[1,1,1],[1,1,1]] Output: 2 Explanation: The pyramidal plot is shown in blue, and the inverse pyramidal plot is shown in red. Hence the total number of plots is 1 + 1 = 2.
Example 3:
Input: grid = [[1,1,1,1,0],[1,1,1,1,1],[1,1,1,1,1],[0,1,0,0,1]] Output: 13 Explanation: There are 7 pyramidal plots, 3 of which are shown in the 2nd and 3rd figures. There are 6 inverse pyramidal plots, 2 of which are shown in the last figure. The total number of plots is 7 + 6 = 13.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 10001 <= m * n <= 105grid[i][j] is either 0 or 1.Problem summary: A farmer has a rectangular grid of land with m rows and n columns that can be divided into unit cells. Each cell is either fertile (represented by a 1) or barren (represented by a 0). All cells outside the grid are considered barren. A pyramidal plot of land can be defined as a set of cells with the following criteria: The number of cells in the set has to be greater than 1 and all cells must be fertile. The apex of a pyramid is the topmost cell of the pyramid. The height of a pyramid is the number of rows it covers. Let (r, c) be the apex of the pyramid, and its height be h. Then, the plot comprises of cells (i, j) where r <= i <= r + h - 1 and c - (i - r) <= j <= c + (i - r). An inverse pyramidal plot of land can be defined as a set of cells with similar criteria: The number of cells in the set has to be greater than 1 and all cells must be fertile. The apex of an inverse pyramid is
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming
[[0,1,1,0],[1,1,1,1]]
[[1,1,1],[1,1,1]]
[[1,1,1,1,0],[1,1,1,1,1],[1,1,1,1,1],[0,1,0,0,1]]
count-square-submatrices-with-all-ones)get-biggest-three-rhombus-sums-in-a-grid)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2088: Count Fertile Pyramids in a Land
class Solution {
public int countPyramids(int[][] grid) {
int m = grid.length, n = grid[0].length;
int[][] f = new int[m][n];
int ans = 0;
for (int i = m - 1; i >= 0; --i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 0) {
f[i][j] = -1;
} else if (i == m - 1 || j == 0 || j == n - 1) {
f[i][j] = 0;
} else {
f[i][j] = Math.min(f[i + 1][j - 1], Math.min(f[i + 1][j], f[i + 1][j + 1])) + 1;
ans += f[i][j];
}
}
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 0) {
f[i][j] = -1;
} else if (i == 0 || j == 0 || j == n - 1) {
f[i][j] = 0;
} else {
f[i][j] = Math.min(f[i - 1][j - 1], Math.min(f[i - 1][j], f[i - 1][j + 1])) + 1;
ans += f[i][j];
}
}
}
return ans;
}
}
// Accepted solution for LeetCode #2088: Count Fertile Pyramids in a Land
func countPyramids(grid [][]int) (ans int) {
m, n := len(grid), len(grid[0])
f := make([][]int, m)
for i := range f {
f[i] = make([]int, n)
}
for i := m - 1; i >= 0; i-- {
for j := 0; j < n; j++ {
if grid[i][j] == 0 {
f[i][j] = -1
} else if i == m-1 || j == 0 || j == n-1 {
f[i][j] = 0
} else {
f[i][j] = min(f[i+1][j-1], min(f[i+1][j], f[i+1][j+1])) + 1
ans += f[i][j]
}
}
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if grid[i][j] == 0 {
f[i][j] = -1
} else if i == 0 || j == 0 || j == n-1 {
f[i][j] = 0
} else {
f[i][j] = min(f[i-1][j-1], min(f[i-1][j], f[i-1][j+1])) + 1
ans += f[i][j]
}
}
}
return
}
# Accepted solution for LeetCode #2088: Count Fertile Pyramids in a Land
class Solution:
def countPyramids(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
f = [[0] * n for _ in range(m)]
ans = 0
for i in range(m - 1, -1, -1):
for j in range(n):
if grid[i][j] == 0:
f[i][j] = -1
elif not (i == m - 1 or j == 0 or j == n - 1):
f[i][j] = min(f[i + 1][j - 1], f[i + 1][j], f[i + 1][j + 1]) + 1
ans += f[i][j]
for i in range(m):
for j in range(n):
if grid[i][j] == 0:
f[i][j] = -1
elif i == 0 or j == 0 or j == n - 1:
f[i][j] = 0
else:
f[i][j] = min(f[i - 1][j - 1], f[i - 1][j], f[i - 1][j + 1]) + 1
ans += f[i][j]
return ans
// Accepted solution for LeetCode #2088: Count Fertile Pyramids in a Land
/**
* [2088] Count Fertile Pyramids in a Land
*
* A farmer has a rectangular grid of land with m rows and n columns that can be divided into unit cells. Each cell is either fertile (represented by a 1) or barren (represented by a 0). All cells outside the grid are considered barren.
* A pyramidal plot of land can be defined as a set of cells with the following criteria:
* <ol>
* The number of cells in the set has to be greater than 1 and all cells must be fertile.
* The apex of a pyramid is the topmost cell of the pyramid. The height of a pyramid is the number of rows it covers. Let (r, c) be the apex of the pyramid, and its height be h. Then, the plot comprises of cells (i, j) where r <= i <= r + h - 1 and c - (i - r) <= j <= c + (i - r).
* </ol>
* An inverse pyramidal plot of land can be defined as a set of cells with similar criteria:
* <ol>
* The number of cells in the set has to be greater than 1 and all cells must be fertile.
* The apex of an inverse pyramid is the bottommost cell of the inverse pyramid. The height of an inverse pyramid is the number of rows it covers. Let (r, c) be the apex of the pyramid, and its height be h. Then, the plot comprises of cells (i, j) where r - h + 1 <= i <= r and c - (r - i) <= j <= c + (r - i).
* </ol>
* Some examples of valid and invalid pyramidal (and inverse pyramidal) plots are shown below. Black cells indicate fertile cells.
* <img src="https://assets.leetcode.com/uploads/2021/11/08/image.png" style="width: 700px; height: 156px;" />
* Given a 0-indexed m x n binary matrix grid representing the farmland, return the total number of pyramidal and inverse pyramidal plots that can be found in grid.
*
* Example 1:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/12/22/1.JPG" style="width: 575px; height: 109px;" />
* Input: grid = [[0,1,1,0],[1,1,1,1]]
* Output: 2
* Explanation: The 2 possible pyramidal plots are shown in blue and red respectively.
* There are no inverse pyramidal plots in this grid.
* Hence total number of pyramidal and inverse pyramidal plots is 2 + 0 = 2.
*
* Example 2:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/12/22/2.JPG" style="width: 502px; height: 120px;" />
* Input: grid = [[1,1,1],[1,1,1]]
* Output: 2
* Explanation: The pyramidal plot is shown in blue, and the inverse pyramidal plot is shown in red.
* Hence the total number of plots is 1 + 1 = 2.
*
* Example 3:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/12/22/3.JPG" style="width: 676px; height: 148px;" />
* Input: grid = [[1,1,1,1,0],[1,1,1,1,1],[1,1,1,1,1],[0,1,0,0,1]]
* Output: 13
* Explanation: There are 7 pyramidal plots, 3 of which are shown in the 2nd and 3rd figures.
* There are 6 inverse pyramidal plots, 2 of which are shown in the last figure.
* The total number of plots is 7 + 6 = 13.
*
*
* Constraints:
*
* m == grid.length
* n == grid[i].length
* 1 <= m, n <= 1000
* 1 <= m * n <= 10^5
* grid[i][j] is either 0 or 1.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/count-fertile-pyramids-in-a-land/
// discuss: https://leetcode.com/problems/count-fertile-pyramids-in-a-land/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn count_pyramids(grid: Vec<Vec<i32>>) -> i32 {
0
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_2088_example_1() {
let grid = vec![vec![0, 1, 1, 0], vec![1, 1, 1, 1]];
let result = 2;
assert_eq!(Solution::count_pyramids(grid), result);
}
#[test]
#[ignore]
fn test_2088_example_2() {
let grid = vec![vec![1, 1, 1], vec![1, 1, 1]];
let result = 3;
assert_eq!(Solution::count_pyramids(grid), result);
}
#[test]
#[ignore]
fn test_2088_example_3() {
let grid = vec![
vec![1, 1, 1, 1, 0],
vec![1, 1, 1, 1, 1],
vec![1, 1, 1, 1, 1],
vec![0, 1, 0, 0, 1],
];
let result = 13;
assert_eq!(Solution::count_pyramids(grid), result);
}
}
// Accepted solution for LeetCode #2088: Count Fertile Pyramids in a Land
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #2088: Count Fertile Pyramids in a Land
// class Solution {
// public int countPyramids(int[][] grid) {
// int m = grid.length, n = grid[0].length;
// int[][] f = new int[m][n];
// int ans = 0;
// for (int i = m - 1; i >= 0; --i) {
// for (int j = 0; j < n; ++j) {
// if (grid[i][j] == 0) {
// f[i][j] = -1;
// } else if (i == m - 1 || j == 0 || j == n - 1) {
// f[i][j] = 0;
// } else {
// f[i][j] = Math.min(f[i + 1][j - 1], Math.min(f[i + 1][j], f[i + 1][j + 1])) + 1;
// ans += f[i][j];
// }
// }
// }
// for (int i = 0; i < m; ++i) {
// for (int j = 0; j < n; ++j) {
// if (grid[i][j] == 0) {
// f[i][j] = -1;
// } else if (i == 0 || j == 0 || j == n - 1) {
// f[i][j] = 0;
// } else {
// f[i][j] = Math.min(f[i - 1][j - 1], Math.min(f[i - 1][j], f[i - 1][j + 1])) + 1;
// ans += f[i][j];
// }
// }
// }
// return ans;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.