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 virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an m x n binary grid isInfected, where isInfected[i][j] == 0 represents uninfected cells, and isInfected[i][j] == 1 represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two 4-directionally adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There will never be a tie.
Return the number of walls used to quarantine all the infected regions. If the world will become fully infected, return the number of walls used.
Example 1:
Input: isInfected = [[0,1,0,0,0,0,0,1],[0,1,0,0,0,0,0,1],[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0]] Output: 10 Explanation: There are 2 contaminated regions. On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is: On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
Example 2:
Input: isInfected = [[1,1,1],[1,0,1],[1,1,1]] Output: 4 Explanation: Even though there is only one cell saved, there are 4 walls built. Notice that walls are only built on the shared boundary of two different cells.
Example 3:
Input: isInfected = [[1,1,1,0,0,0,0,0,0],[1,0,1,0,1,1,1,1,1],[1,1,1,0,0,0,0,0,0]] Output: 13 Explanation: The region on the left only builds two new walls.
Constraints:
m == isInfected.lengthn == isInfected[i].length1 <= m, n <= 50isInfected[i][j] is either 0 or 1.Problem summary: A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls. The world is modeled as an m x n binary grid isInfected, where isInfected[i][j] == 0 represents uninfected cells, and isInfected[i][j] == 1 represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two 4-directionally adjacent cells, on the shared boundary. Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There will never be a tie. Return the number of walls used to quarantine all the infected regions. If the world will become fully infected, return the number of walls used.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
[[0,1,0,0,0,0,0,1],[0,1,0,0,0,0,0,1],[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0]]
[[1,1,1],[1,0,1],[1,1,1]]
[[1,1,1,0,0,0,0,0,0],[1,0,1,0,1,1,1,1,1],[1,1,1,0,0,0,0,0,0]]
count-the-number-of-infection-sequences)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #749: Contain Virus
class Solution {
private static final int[] DIRS = {-1, 0, 1, 0, -1};
private List<Integer> c = new ArrayList<>();
private List<List<Integer>> areas = new ArrayList<>();
private List<Set<Integer>> boundaries = new ArrayList<>();
private int[][] infected;
private boolean[][] vis;
private int m;
private int n;
public int containVirus(int[][] isInfected) {
infected = isInfected;
m = infected.length;
n = infected[0].length;
vis = new boolean[m][n];
int ans = 0;
while (true) {
for (boolean[] row : vis) {
Arrays.fill(row, false);
}
c.clear();
areas.clear();
boundaries.clear();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (infected[i][j] == 1 && !vis[i][j]) {
c.add(0);
areas.add(new ArrayList<>());
boundaries.add(new HashSet<>());
dfs(i, j);
}
}
}
if (areas.isEmpty()) {
break;
}
int idx = max(boundaries);
ans += c.get(idx);
for (int t = 0; t < areas.size(); ++t) {
if (t == idx) {
for (int v : areas.get(t)) {
int i = v / n, j = v % n;
infected[i][j] = -1;
}
} else {
for (int v : areas.get(t)) {
int i = v / n, j = v % n;
for (int k = 0; k < 4; ++k) {
int x = i + DIRS[k], y = j + DIRS[k + 1];
if (x >= 0 && x < m && y >= 0 && y < n && infected[x][y] == 0) {
infected[x][y] = 1;
}
}
}
}
}
}
return ans;
}
private int max(List<Set<Integer>> boundaries) {
int idx = 0;
int mx = boundaries.get(0).size();
for (int i = 1; i < boundaries.size(); ++i) {
int t = boundaries.get(i).size();
if (mx < t) {
mx = t;
idx = i;
}
}
return idx;
}
private void dfs(int i, int j) {
vis[i][j] = true;
int idx = areas.size() - 1;
areas.get(idx).add(i * n + j);
for (int k = 0; k < 4; ++k) {
int x = i + DIRS[k], y = j + DIRS[k + 1];
if (x >= 0 && x < m && y >= 0 && y < n) {
if (infected[x][y] == 1 && !vis[x][y]) {
dfs(x, y);
} else if (infected[x][y] == 0) {
c.set(idx, c.get(idx) + 1);
boundaries.get(idx).add(x * n + y);
}
}
}
}
}
// Accepted solution for LeetCode #749: Contain Virus
func containVirus(isInfected [][]int) int {
m, n := len(isInfected), len(isInfected[0])
ans := 0
dirs := []int{-1, 0, 1, 0, -1}
max := func(boundaries []map[int]bool) int {
idx := 0
mx := len(boundaries[0])
for i, v := range boundaries {
t := len(v)
if mx < t {
mx = t
idx = i
}
}
return idx
}
for {
vis := make([][]bool, m)
for i := range vis {
vis[i] = make([]bool, n)
}
areas := []map[int]bool{}
boundaries := []map[int]bool{}
c := []int{}
var dfs func(i, j int)
dfs = func(i, j int) {
vis[i][j] = true
idx := len(areas) - 1
areas[idx][i*n+j] = true
for k := 0; k < 4; k++ {
x, y := i+dirs[k], j+dirs[k+1]
if x >= 0 && x < m && y >= 0 && y < n {
if isInfected[x][y] == 1 && !vis[x][y] {
dfs(x, y)
} else if isInfected[x][y] == 0 {
c[idx]++
boundaries[idx][x*n+y] = true
}
}
}
}
for i, row := range isInfected {
for j, v := range row {
if v == 1 && !vis[i][j] {
areas = append(areas, map[int]bool{})
boundaries = append(boundaries, map[int]bool{})
c = append(c, 0)
dfs(i, j)
}
}
}
if len(areas) == 0 {
break
}
idx := max(boundaries)
ans += c[idx]
for t, area := range areas {
if t == idx {
for v := range area {
i, j := v/n, v%n
isInfected[i][j] = -1
}
} else {
for v := range area {
i, j := v/n, v%n
for k := 0; k < 4; k++ {
x, y := i+dirs[k], j+dirs[k+1]
if x >= 0 && x < m && y >= 0 && y < n && isInfected[x][y] == 0 {
isInfected[x][y] = 1
}
}
}
}
}
}
return ans
}
# Accepted solution for LeetCode #749: Contain Virus
class Solution:
def containVirus(self, isInfected: List[List[int]]) -> int:
def dfs(i, j):
vis[i][j] = True
areas[-1].append((i, j))
for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]:
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n:
if isInfected[x][y] == 1 and not vis[x][y]:
dfs(x, y)
elif isInfected[x][y] == 0:
c[-1] += 1
boundaries[-1].add((x, y))
m, n = len(isInfected), len(isInfected[0])
ans = 0
while 1:
vis = [[False] * n for _ in range(m)]
areas = []
c = []
boundaries = []
for i, row in enumerate(isInfected):
for j, v in enumerate(row):
if v == 1 and not vis[i][j]:
areas.append([])
boundaries.append(set())
c.append(0)
dfs(i, j)
if not areas:
break
idx = boundaries.index(max(boundaries, key=len))
ans += c[idx]
for k, area in enumerate(areas):
if k == idx:
for i, j in area:
isInfected[i][j] = -1
else:
for i, j in area:
for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]:
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n and isInfected[x][y] == 0:
isInfected[x][y] = 1
return ans
// Accepted solution for LeetCode #749: Contain Virus
/**
* [0749] Contain Virus
*
* A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
* The world is modeled as an m x n binary grid isInfected, where isInfected[i][j] == 0 represents uninfected cells, and isInfected[i][j] == 1 represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two 4-directionally adjacent cells, on the shared boundary.
* Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There will never be a tie.
* Return the number of walls used to quarantine all the infected regions. If the world will become fully infected, return the number of walls used.
*
* Example 1:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/06/01/virus11-grid.jpg" style="width: 500px; height: 255px;" />
* Input: isInfected = [[0,1,0,0,0,0,0,1],[0,1,0,0,0,0,0,1],[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0]]
* Output: 10
* Explanation: There are 2 contaminated regions.
* On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/06/01/virus12edited-grid.jpg" style="width: 500px; height: 257px;" />
* On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
* <img alt="" src="https://assets.leetcode.com/uploads/2021/06/01/virus13edited-grid.jpg" style="width: 500px; height: 261px;" />
*
* Example 2:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/06/01/virus2-grid.jpg" style="width: 653px; height: 253px;" />
* Input: isInfected = [[1,1,1],[1,0,1],[1,1,1]]
* Output: 4
* Explanation: Even though there is only one cell saved, there are 4 walls built.
* Notice that walls are only built on the shared boundary of two different cells.
*
* Example 3:
*
* Input: isInfected = [[1,1,1,0,0,0,0,0,0],[1,0,1,0,1,1,1,1,1],[1,1,1,0,0,0,0,0,0]]
* Output: 13
* Explanation: The region on the left only builds two new walls.
*
*
* Constraints:
*
* m == isInfected.length
* n == isInfected[i].length
* 1 <= m, n <= 50
* isInfected[i][j] is either 0 or 1.
* There is always a contiguous viral region throughout the described process that will infect strictly more uncontaminated squares in the next round.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/contain-virus/
// discuss: https://leetcode.com/problems/contain-virus/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
// Credit: https://leetcode.com/problems/contain-virus/discuss/892024/Rust-translated-8ms-100
const DIRS: [i32; 5] = [0, -1, 0, 1, 0];
impl Solution {
pub fn contain_virus(is_infected: Vec<Vec<i32>>) -> i32 {
let mut is_infected = is_infected;
let mut visited = std::collections::HashSet::<i32>::new();
let mut regions = Vec::<std::collections::HashSet<i32>>::new();
let mut frontiers = Vec::<std::collections::HashSet<i32>>::new();
let mut perimeters = Vec::<i32>::new();
let m = is_infected.len();
let n = is_infected[0].len();
let mut result = 0;
loop {
visited.clear();
regions.clear();
frontiers.clear();
perimeters.clear();
for r in 0..m {
for c in 0..n {
if is_infected[r][c] == 1 && !visited.contains(&((r * n + c) as i32)) {
regions.push(std::collections::HashSet::new());
frontiers.push(std::collections::HashSet::new());
perimeters.push(0);
Self::dfs_helper(
&mut is_infected,
&mut regions,
&mut frontiers,
&mut perimeters,
&mut visited,
r as i32,
c as i32,
);
}
}
}
if regions.is_empty() {
break;
}
let mut triage_index = 0;
for i in 0..frontiers.len() {
if frontiers[triage_index].len() < frontiers[i].len() {
triage_index = i;
}
}
result += perimeters.get(triage_index).unwrap_or_else(|| &0);
for i in 0..regions.len() {
if i == triage_index {
for &code in ®ions[i] {
is_infected[code as usize / n][code as usize % n] = -1;
}
} else {
for &code in ®ions[i] {
let r = code / n as i32;
let c = code % n as i32;
for k in 0..4 {
let nr = r + DIRS[k];
let nc = c + DIRS[k + 1];
if nr >= 0
&& nr < m as i32
&& nc >= 0
&& nc < n as i32
&& is_infected[nr as usize][nc as usize] == 0
{
is_infected[nr as usize][nc as usize] = 1;
}
}
}
}
}
}
result
}
fn dfs_helper(
is_infected: &mut Vec<Vec<i32>>,
regions: &mut Vec<std::collections::HashSet<i32>>,
frontiers: &mut Vec<std::collections::HashSet<i32>>,
perimeters: &mut Vec<i32>,
visited: &mut std::collections::HashSet<i32>,
r: i32,
c: i32,
) {
let m = is_infected.len();
let n = is_infected[0].len();
if !visited.contains(&(r * n as i32 + c as i32)) {
visited.insert(r * n as i32 + c as i32);
}
let n2 = regions.len();
regions[n2 - 1].insert(r * n as i32 + c as i32);
for k in 0..4 {
let nr = r + DIRS[k];
let nc = c + DIRS[k + 1];
if nr >= 0 && nr < m as i32 && nc >= 0 && nc < n as i32 {
if is_infected[nr as usize][nc as usize] == 1
&& !visited.contains(&(nr * n as i32 + nc as i32))
{
Self::dfs_helper(is_infected, regions, frontiers, perimeters, visited, nr, nc);
} else if is_infected[nr as usize][nc as usize] == 0 {
frontiers[n2 - 1].insert(nr * n as i32 + nc);
perimeters[n2 - 1] += 1;
}
}
}
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_0749_example_1() {
let is_infected = vec![
vec![0, 1, 0, 0, 0, 0, 0, 1],
vec![0, 1, 0, 0, 0, 0, 0, 1],
vec![0, 0, 0, 0, 0, 0, 0, 1],
vec![0, 0, 0, 0, 0, 0, 0, 0],
];
let result = 10;
assert_eq!(Solution::contain_virus(is_infected), result);
}
#[test]
fn test_0749_example_2() {
let is_infected = vec![vec![1, 1, 1], vec![1, 0, 1], vec![1, 1, 1]];
let result = 4;
assert_eq!(Solution::contain_virus(is_infected), result);
}
#[test]
fn test_0749_example_3() {
let is_infected = vec![
vec![1, 1, 1, 0, 0, 0, 0, 0, 0],
vec![1, 0, 1, 0, 1, 1, 1, 1, 1],
vec![1, 1, 1, 0, 0, 0, 0, 0, 0],
];
let result = 13;
assert_eq!(Solution::contain_virus(is_infected), result);
}
}
// Accepted solution for LeetCode #749: Contain Virus
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #749: Contain Virus
// class Solution {
// private static final int[] DIRS = {-1, 0, 1, 0, -1};
// private List<Integer> c = new ArrayList<>();
// private List<List<Integer>> areas = new ArrayList<>();
// private List<Set<Integer>> boundaries = new ArrayList<>();
// private int[][] infected;
// private boolean[][] vis;
// private int m;
// private int n;
//
// public int containVirus(int[][] isInfected) {
// infected = isInfected;
// m = infected.length;
// n = infected[0].length;
// vis = new boolean[m][n];
// int ans = 0;
// while (true) {
// for (boolean[] row : vis) {
// Arrays.fill(row, false);
// }
// c.clear();
// areas.clear();
// boundaries.clear();
// for (int i = 0; i < m; ++i) {
// for (int j = 0; j < n; ++j) {
// if (infected[i][j] == 1 && !vis[i][j]) {
// c.add(0);
// areas.add(new ArrayList<>());
// boundaries.add(new HashSet<>());
// dfs(i, j);
// }
// }
// }
// if (areas.isEmpty()) {
// break;
// }
// int idx = max(boundaries);
// ans += c.get(idx);
// for (int t = 0; t < areas.size(); ++t) {
// if (t == idx) {
// for (int v : areas.get(t)) {
// int i = v / n, j = v % n;
// infected[i][j] = -1;
// }
// } else {
// for (int v : areas.get(t)) {
// int i = v / n, j = v % n;
// for (int k = 0; k < 4; ++k) {
// int x = i + DIRS[k], y = j + DIRS[k + 1];
// if (x >= 0 && x < m && y >= 0 && y < n && infected[x][y] == 0) {
// infected[x][y] = 1;
// }
// }
// }
// }
// }
// }
// return ans;
// }
//
// private int max(List<Set<Integer>> boundaries) {
// int idx = 0;
// int mx = boundaries.get(0).size();
// for (int i = 1; i < boundaries.size(); ++i) {
// int t = boundaries.get(i).size();
// if (mx < t) {
// mx = t;
// idx = i;
// }
// }
// return idx;
// }
//
// private void dfs(int i, int j) {
// vis[i][j] = true;
// int idx = areas.size() - 1;
// areas.get(idx).add(i * n + j);
// for (int k = 0; k < 4; ++k) {
// int x = i + DIRS[k], y = j + DIRS[k + 1];
// if (x >= 0 && x < m && y >= 0 && y < n) {
// if (infected[x][y] == 1 && !vis[x][y]) {
// dfs(x, y);
// } else if (infected[x][y] == 0) {
// c.set(idx, c.get(idx) + 1);
// boundaries.get(idx).add(x * n + y);
// }
// }
// }
// }
// }
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
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.