Maximum Connected Land Sum and Coordinates

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given a rectangular m x n integer matrix grid, each entry grid[r][c] describes one square of terrain: 0 indicates water, while any non-zero integer (positive or negative) indicates land carrying that numeric weight.

Two land squares belong to the same island when they share a top, bottom, left, or right border (4-way orthogonal adjacency; squares touching only diagonally across a corner are not connected). An island is a maximal connected group of non-zero squares.

Implement maximum_island_sums(grid) to evaluate islands under two rules and return both results in a single dictionary:

  1. "all" — Every island in grid is eligible, including islands that contain negative weights or have a zero or negative total sum.
  2. "nonnegative" — An island is eligible only when none of its squares has a negative value (every square in the island is strictly positive, since 0 is water). Any island containing even one negative square must be excluded as a whole.

For each mode ("all" and "nonnegative"), map the key to a dictionary with three entries:

  • "sum": the largest sum of square weights over all eligible islands, or None when no eligible island exists.
  • "index": [r, c] (0-indexed) of the winning island's earliest square in row-major scan order (smallest r, breaking ties by smallest c), or None when no eligible island exists.
  • "last_index": [r, c] (0-indexed) of the winning island's latest square in row-major scan order (largest r, breaking ties by largest c), or None when no eligible island exists.

Tie-breaking rule: Whenever multiple eligible islands share the exact same maximum "sum", choose the island whose "last_index" comes latest in row-major order (larger r wins first; if r is equal, larger c wins).

Examples

Example 1

Input:
grid = [
  [6, -2, 0],
  [5,  0, 4],
  [0,  0, 3]
]

Output:
{
  "all": {"sum": 9, "index": [0, 0], "last_index": [1, 0]},
  "nonnegative": {"sum": 7, "index": [1, 2], "last_index": [2, 2]}
}

Explanation: There are two islands because (0, 1) and (1, 2) meet only at a corner. The upper-left L-shaped island {(0, 0), (0, 1), (1, 0)} totals 6 + (-2) + 5 = 9 with earliest square [0, 0] and latest square [1, 0], so it wins "all". Because (0, 1) = -2 is negative, that entire island is disqualified from "nonnegative", leaving the right-hand island {(1, 2), (2, 2)} with sum 4 + 3 = 7 to win "nonnegative".

Example 2

Input:
grid = [
  [4, 4, 0],
  [0, 0, 5],
  [8, 0, 3]
]

Output:
{
  "all": {"sum": 8, "index": [1, 2], "last_index": [2, 2]},
  "nonnegative": {"sum": 8, "index": [1, 2], "last_index": [2, 2]}
}

Explanation: Three separate positive islands exist: {(0, 0), (0, 1)} (sum 8, last_index [0, 1]), {(1, 2), (2, 2)} (sum 8, last_index [2, 2]), and {(2, 0)} (sum 8, last_index [2, 0]). All three tie on sum 8; comparing last_index in row-major order gives [0, 1] < [2, 0] < [2, 2], so {(1, 2), (2, 2)} wins both modes.

Example 3

Input:
grid = [
  [-3, -1],
  [ 0,  0]
]

Output:
{
  "all": {"sum": -4, "index": [0, 0], "last_index": [0, 1]},
  "nonnegative": {"sum": None, "index": None, "last_index": None}
}

Explanation: The sole island {(0, 0), (0, 1)} sums to -4, winning "all" with index = [0, 0] and last_index = [0, 1]. Because no island is free of negative squares, "nonnegative" returns None for all three fields.

Constraints

  • 0 <= len(grid) <= 500
  • 0 <= len(grid[r]) <= 500, and every row has the same column count
  • -10^4 <= grid[r][c] <= 10^4
  • Aim for O(m * n) time complexity and O(m * n) auxiliary space without exceeding Python's call-stack limit on large connected regions

Step-by-step walkthrough

  1. Understand the problem and output shape

    We are given an m x n grid of integers where 0 represents water and any non-zero integer (positive or negative) represents land. Land cells belong to the same island when connected up, down, left, or right (4-directional edge sharing; diagonal corners do not connect).

    Our function returns one dictionary containing two results—"all" (considering every island) and "nonnegative" (ignoring any island that contains even a single negative cell):

    • "sum": the maximum island sum under that rule,
    • "index": [r, c] of the winning island's first cell in row-major order (smallest r, breaking ties by smallest c),
    • "last_index": [r, c] of the winning island's last cell in row-major order (largest r, breaking ties by largest c). When two islands tie on "sum", the island with the larger "last_index" wins.
    • If no eligible island exists, all three fields are None.
  2. Why naive exploration and recursion fall short

    If we started a fresh traversal from every non-zero cell without remembering what we already visited, an island of k cells would be traversed k separate times, turning a single grid-wide island into O((m * n)^2) work. Marking cells in a visited boolean matrix ensures every cell is explored once, dropping total work to O(m * n).

    Even with visited, writing a recursive depth-first search in Python has a hidden trap: Python's call stack defaults to 1,000 frames, whereas a 200 x 200 island has 40,000 cells and crashes with RecursionError. Using an explicit Python list as an iterative stack avoids recursion limits completely.

  3. Key idea: gather every island fact in one iterative pass

    When our row-major scan (row = 0..m-1, col = 0..n-1) hits an unvisited land cell (start_row, start_col), we immediately know (start_row, start_col) is that island's first cell in row-major order—if an earlier cell belonged to this island, our scan would have hit it earlier!

    During the single iterative flood fill from (start_row, start_col), we compute three things at once: 1. total_sum: the sum of all cell values in the island. 2. has_negative: True if any cell in the island has value < 0 (which disqualifies the whole island from "nonnegative"). 3. last_cell: the maximum (row, col) tuple visited. Notice why we must compare (row, col) > last_cell explicitly rather than taking the last cell popped from the stack:

    Grid:
      col:  0  1  2
    row 0:  0  4  1      Island cells: (0,1), (0,2), (1,1), (2,0), (2,1)
    row 1:  0  1  0      - Row-major first cell ("index"):      [0, 1]
    row 2:  1  1  0      - Row-major last cell  ("last_index"): [2, 1]
                         (A DFS or BFS might visit (2, 0) last, which is NOT [2, 1]!)
    
  4. Code the iterative island exploration

    Two invariants in explore_island prevent classic graph bugs: - Check grid[next_row][next_col] != 0, not > 0: Negative cells are land! Treating negative cells as water would falsely break one island into disconnected pieces or hide a negative cell that should disqualify the "nonnegative" mode. - Mark visited[next_row][next_col] = True when pushing, not when popping: If two already-visited cells share an unvisited neighbor, marking on push prevents pushing that neighbor onto stack twice and adding its value to total_sum twice.

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    # 4-directional edge neighbors: down, up, right, left (diagonals do not connect).
    DIRECTIONS = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    
    
    def explore_island(
        grid: List[List[int]],
        start_row: int,
        start_col: int,
        visited: List[List[bool]],
    ) -> Tuple[int, bool, Tuple[int, int]]:
        """Traverse one connected island iteratively and return (total_sum, has_negative, last_cell)."""
        rows = len(grid)
        cols = len(grid[0])
    
        # stack: explicit DFS worklist of (row, col) land coordinates, e.g. [(0, 1), (1, 0)].
        # Using a list stack avoids Python's ~1000-frame recursion limit on large islands.
        stack: List[Tuple[int, int]] = [(start_row, start_col)]
        visited[start_row][start_col] = True
    
        total_sum = 0
        has_negative = False
        # last_cell: largest (row, col) tuple seen in row-major order (compares row first, then col).
        last_cell = (start_row, start_col)
    
        while stack:
            row, col = stack.pop()
            cell_value = grid[row][col]
            total_sum += cell_value
    
            if cell_value < 0:
                has_negative = True
            # Track the row-major maximum explicitly; DFS pop order is NOT row-major order.
            if (row, col) > last_cell:
                last_cell = (row, col)
    
            for d_row, d_col in DIRECTIONS:
                next_row = row + d_row
                next_col = col + d_col
                in_bounds = 0 <= next_row < rows and 0 <= next_col < cols
                # Check != 0 (not > 0): negative cells are still land and connect parts of an island.
                if in_bounds and grid[next_row][next_col] != 0 and not visited[next_row][next_col]:
                    # Mark visited BEFORE pushing so two neighbors never push and sum the same cell twice.
                    visited[next_row][next_col] = True
                    stack.append((next_row, next_col))
    
        return total_sum, has_negative, last_cell
    
  5. Code the tie-breaker and output formatter

    Why initialize best_all and best_nonnegative to None instead of 0? Because in a grid like [[-2, 0, -1]], the best overall island has sum -1 < 0! Starting at 0 would ignore -1 and pretend no island existed.

    In Python, comparing 2-tuples (r1, c1) > (r2, c2) compares r1 against r2 first, and compares c1 against c2 only when r1 == r2—which is the exact definition of row-major order. Since distinct islands never share cells, no two islands ever share the same "last" tuple, so ties are always broken uniquely.

    def is_better(
        candidate: Dict[str, Any], current_best: Optional[Dict[str, Any]]
    ) -> bool:
        """Return True if `candidate` beats `current_best` by sum, or by row-major last cell on ties."""
        # Start winners at None (not 0) because every island in the grid may have a negative sum.
        if current_best is None:
            return True
        if candidate["sum"] != current_best["sum"]:
            return candidate["sum"] > current_best["sum"]
        return candidate["last"] > current_best["last"]
    
    
    def format_answer(island: Optional[Dict[str, Any]]) -> Dict[str, object]:
        """Convert an internal island summary (or None) into the required output dictionary."""
        if island is None:
            return {"sum": None, "index": None, "last_index": None}
        first_row, first_col = island["first"]
        last_row, last_col = island["last"]
        return {
            "sum": island["sum"],
            "index": [first_row, first_col],
            "last_index": [last_row, last_col],
        }
    
  6. Scan the grid and trace Example 1

    Let's walk through Example 1 step by step:

    Grid:
       6  -2   0
       5   0   4
       0   0   3
    
    1. Scan reaches (0, 0) = 6 (unvisited land):
       - explore_island visits (0,0)=6, (0,1)=-2, (1,0)=5
       - total_sum = 6 - 2 + 5 = 9,  has_negative = True,  first = (0,0),  last = (1,0)
       - best_all         -> {sum: 9, first: (0,0), last: (1,0)}
       - best_nonnegative -> None (skipped because has_negative is True!)
    
    2. Scan skips visited (0,1), water (0,2), visited (1,0), and water (1,1).
    
    3. Scan reaches (1, 2) = 4 (unvisited land):
       - explore_island visits (1,2)=4 and (2,2)=3 (diagonal (0,1) is NOT edge-connected!)
       - total_sum = 4 + 3 = 7,  has_negative = False,  first = (1,2),  last = (2,2)
       - best_all         -> stays {sum: 9, first: (0,0), last: (1,0)}  (9 > 7)
       - best_nonnegative -> {sum: 7, first: (1,2), last: (2,2)}  (first eligible island)
    

    "all" formats to {"sum": 9, "index": [0, 0], "last_index": [1, 0]}, while "nonnegative" formats to {"sum": 7, "index": [1, 2], "last_index": [2, 2]}.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    # 4-directional edge neighbors: down, up, right, left (diagonals do not connect).
    DIRECTIONS = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    
    
    def explore_island(
        grid: List[List[int]],
        start_row: int,
        start_col: int,
        visited: List[List[bool]],
    ) -> Tuple[int, bool, Tuple[int, int]]:
        """Traverse one connected island iteratively and return (total_sum, has_negative, last_cell)."""
        rows = len(grid)
        cols = len(grid[0])
    
        # stack: explicit DFS worklist of (row, col) land coordinates, e.g. [(0, 1), (1, 0)].
        # Using a list stack avoids Python's ~1000-frame recursion limit on large islands.
        stack: List[Tuple[int, int]] = [(start_row, start_col)]
        visited[start_row][start_col] = True
    
        total_sum = 0
        has_negative = False
        # last_cell: largest (row, col) tuple seen in row-major order (compares row first, then col).
        last_cell = (start_row, start_col)
    
        while stack:
            row, col = stack.pop()
            cell_value = grid[row][col]
            total_sum += cell_value
    
            if cell_value < 0:
                has_negative = True
            # Track the row-major maximum explicitly; DFS pop order is NOT row-major order.
            if (row, col) > last_cell:
                last_cell = (row, col)
    
            for d_row, d_col in DIRECTIONS:
                next_row = row + d_row
                next_col = col + d_col
                in_bounds = 0 <= next_row < rows and 0 <= next_col < cols
                # Check != 0 (not > 0): negative cells are still land and connect parts of an island.
                if in_bounds and grid[next_row][next_col] != 0 and not visited[next_row][next_col]:
                    # Mark visited BEFORE pushing so two neighbors never push and sum the same cell twice.
                    visited[next_row][next_col] = True
                    stack.append((next_row, next_col))
    
        return total_sum, has_negative, last_cell
    
    
    def is_better(
        candidate: Dict[str, Any], current_best: Optional[Dict[str, Any]]
    ) -> bool:
        """Return True if `candidate` beats `current_best` by sum, or by row-major last cell on ties."""
        # Start winners at None (not 0) because every island in the grid may have a negative sum.
        if current_best is None:
            return True
        if candidate["sum"] != current_best["sum"]:
            return candidate["sum"] > current_best["sum"]
        return candidate["last"] > current_best["last"]
    
    
    def format_answer(island: Optional[Dict[str, Any]]) -> Dict[str, object]:
        """Convert an internal island summary (or None) into the required output dictionary."""
        if island is None:
            return {"sum": None, "index": None, "last_index": None}
        first_row, first_col = island["first"]
        last_row, last_col = island["last"]
        return {
            "sum": island["sum"],
            "index": [first_row, first_col],
            "last_index": [last_row, last_col],
        }
    
    
    def maximum_island_sums(grid: List[List[int]]) -> Dict[str, Dict[str, object]]:
        rows = len(grid)
        cols = len(grid[0]) if rows > 0 else 0
    
        # visited: m x n boolean matrix ensuring every land cell is explored at most once.
        visited: List[List[bool]] = []
        for _ in range(rows):
            visited.append([False] * cols)
    
        # Each winner stores {"sum": int, "first": (r, c), "last": (r, c)}, or None if none seen yet.
        best_all: Optional[Dict[str, Any]] = None
        best_nonnegative: Optional[Dict[str, Any]] = None
    
        # Scan top-to-bottom, left-to-right (row-major order).
        for row in range(rows):
            for col in range(cols):
                if grid[row][col] == 0 or visited[row][col]:
                    continue
    
                # Because we scan in row-major order, (row, col) is guaranteed to be this island's
                # earliest cell, while explore_island finds its sum, negativity, and latest cell.
                total_sum, has_negative, last_cell = explore_island(grid, row, col, visited)
                island_summary = {
                    "sum": total_sum,
                    "first": (row, col),
                    "last": last_cell,
                }
    
                if is_better(island_summary, best_all):
                    best_all = island_summary
                if not has_negative and is_better(island_summary, best_nonnegative):
                    best_nonnegative = island_summary
    
        return {
            "all": format_answer(best_all),
            "nonnegative": format_answer(best_nonnegative),
        }
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine surveying an archipelago on a grid map where 0 is ocean water, positive numbers are gold deposits, and negative numbers are toxic swamps. Whenever your row-by-row scan spots an uncharted tile of land, you step onto it and walk every tile reachable across shared edges, dropping a chalk mark on each tile so you never visit or count it twice. In graph terms, each island is a connected component (a maximal group of land cells linked by 4-directional edges), walking out from one cell to mark its entire group is a flood fill (implemented here as an iterative depth-first search, or DFS, which uses a last-in-first-out stack of coordinates to explore neighbors), and reading top-to-bottom, left-to-right is row-major order (comparing (r1, c1) against (r2, c2) by row r first, then column c).

Why not launch a fresh search from every land cell without a visited grid, or write a quick 5-line recursive helper? Without visited, an island of k cells gets re-explored k times, degrading a single full-grid island to O((m * n)^2) time. And in Python, recursive DFS pushes one function frame per cell onto the call stack, crashing with RecursionError as soon as an island exceeds ~1,000 cells, whereas an explicit stack list handles tens of thousands of cells effortlessly while computing both "all" and "nonnegative" winners in the exact same pass.

Here is a step-by-step trace on Example 1 (3 x 3) showing how both modes diverge when an island contains a negative tile:

Grid:
  [ 6, -2,  0 ]
  [ 5,  0,  4 ]
  [ 0,  0,  3 ]

1. Scan hits (0, 0) = 6:
   - Flood fill visits (0, 0) = 6, (0, 1) = -2, and (1, 0) = 5.
   - Island 1 summary: sum = 9, has_negative = True, first = (0, 0), last = (1, 0).
   - "all" winner         -> sum 9, index [0, 0], last_index [1, 0]
   - "nonnegative" winner -> None (disqualified because of -2!)

2. Scan skips visited/water tiles, then hits (1, 2) = 4:
   - Flood fill visits (1, 2) = 4 and (2, 2) = 3.
   - Island 2 summary: sum = 7, has_negative = False, first = (1, 2), last = (2, 2).
   - "all" winner         -> stays Island 1 (9 > 7)
   - "nonnegative" winner -> Island 2: sum 7, index [1, 2], last_index [2, 2]

Complexity

For a grid with m rows and n columns (m * n total cells):

  • Time: O(m * n). The outer loops inspect each of the m * n cells once in O(1) time. Because we set visited[r][c] = True the moment a land cell is pushed onto stack, each land cell enters and leaves stack at most once and checks at most 4 neighbors, doing constant work per cell across the entire run.
  • Space: O(m * n). The visited matrix stores m * n booleans, and in the worst case (one large island covering the grid) stack holds up to O(m * n) coordinate tuples at once.

Edge cases

  • All-water or empty grids ([[0, 0]], [], [[]]): Neither winner is ever updated from None, so both "all" and "nonnegative" return {"sum": None, "index": None, "last_index": None}.
  • Every island contains negative cells ([[-2, 0, -1]]): "all" picks the least negative island (sum: -1 at [0, 2]) because best_all starts at None rather than 0, while "nonnegative" returns all Nones.
  • Island whose positive and negative cells sum to 0 ([[2, -2]]): Treated as a real island with sum: 0 in "all" (if island is None: checks identity with None, never truthiness of sum), and excluded from "nonnegative".
  • Ties on maximum sum ([[3, 0, 1, 2]]): Both islands sum to 3; the right island's last_index (0, 3) beats (0, 0), so index: [0, 2], last_index: [0, 3] wins.
  • Diagonal-only contact ([[1, 0], [0, 1]]): Corner neighbors are separate islands because DIRECTIONS contains only the 4 orthogonal steps.
  • L-shaped or T-shaped islands ([[0, 4, 1], [0, 1, 0], [1, 1, 0]]): index is [0, 1] (not leftmost column 0), and last_index is [2, 1] (computed via max tuple, not last popped DFS node [2, 0]).

Common mistakes

  • Checking grid[r][c] > 0 instead of grid[r][c] != 0 when expanding neighbors: That treats negative tiles as water, splitting islands apart and letting positive pieces sneak into "nonnegative"!
  • Initializing best_sum = 0: Fails whenever all islands have negative sums (or sum 0), confusing "best sum is 0" with "no island exists."
  • Marking visited on pop instead of on push: In a 2 x 2 square of land, (0, 1) and (1, 0) will both push (1, 1) onto the stack before (1, 1) is popped, counting (1, 1)'s value twice!
  • Using the last cell visited by DFS/BFS as last_index: Stack/queue traversal order depends on neighbor-loop order, not row-major order; always maintain last_cell = max(last_cell, (row, col)).
  • Writing recursive DFS in Python: Hits RecursionError on any island larger than ~1,000 cells (such as a 200 x 200 block).

Follow-up questions

  • How would the implementation change if corners also connected land tiles (8-directional adjacency)? You only need to append the four diagonal offsets (1, 1), (1, -1), (-1, 1), (-1, -1) to DIRECTIONS. Every invariant—the row-major first cell at (row, col), tuple comparison (r, c) > last_cell for last_index, and O(m * n) time and space—remains completely unchanged, with 8 neighbor checks per popped cell instead of 4.
  • If you are allowed to mutate the input matrix, how can you eliminate the separate visited array? Instead of allocating the m x n visited matrix, store (r, c, original_value) on stack and overwrite grid[r][c] = 0 (turning land into water) immediately when pushing the cell. That removes the visited array completely, though stack itself can still grow to O(m * n) in the worst case on a dense grid.
  • Suppose the grid has millions of rows arriving as a row-by-row stream that cannot fit in memory at once. How would you still find both answers? Process one row at a time using a union-find structure (also called disjoint-set union, a compact table of parent pointers that merges connected groups and tracks group totals in nearly O(1) time per step) holding only the active components touching the previous row and current row (O(n) memory). Each land cell (r, c) merges with its upper (r - 1, c) and left (r, c - 1) land neighbors, combining sum, has_negative, min_first_cell, and max_last_cell at the root. Any component from r - 1 that receives zero cells in row r can never grow again, so you compare it against best_all and best_nonnegative and discard its state immediately!

Follow-up questions

Similar questions

More DocuSign interview questions

All 5 DocuSign questions →