← L&T Mindtree bank

L&T Mindtree · Question 61 · Graphs

Pacific Atlantic Water Flow

GraphsJavacode⏱ O(mn)💾 O(mn)
Service-based

Problem

You are given m x n matrix representing heights. Find cells where water can flow to both oceans.

Approach

DFS uphill from both oceans' borders; the intersection reaches both.

Time O(mn)Space O(mn)

How it works

  1. 1DFS uphill from all Pacific border cells.
  2. 2Repeat from all Atlantic border cells.
  3. 3Cells in both sets reach both oceans.

Sample input / output

Input:
heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
Output:
[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]]

Constraints

1 <= m, n <= 200.

Solution — read it, then walk it

Time O(mn)Space O(mn)Loops 4Branches 3Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeat↻ repeatyes↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE staticList<List<Integer>>pacificAtlantic(int[][…List<List<Integer>> result= new ArrayList<>()if (heights == null ||heights.length == 0)return resultDEFINE m = heights.length,n = heights[0].lengthDEFINE [][] pacific = newboolean[m][n], atlantic =new boolean[m][n]for (int i = 0; i < m;i++)dfs(heights, pacific, i, 0,Integer.MIN_VALUE)dfs(heights, atlantic, i, n- 1, Integer.MIN_VALUE)for (int j = 0; j < n;j++)dfs(heights, pacific, 0, j,Integer.MIN_VALUE)dfs(heights, atlantic, m -1, j, Integer.MIN_VALUE)for (int i = 0; i < m;i++)for (int j = 0; j < n;j++)if (pacific[i][j] &&atlantic[i][j])result.add(Arrays.asList(i,j))RETURN resultDEFINE static voiddfs(int[][] h, boolean[][]visited, int i, int j, in…if (i < 0 || j < 0 ||i >= h.length || j >=h[0].length |…visited[i][j] = truedfs(h, visited, i + 1, j,h[i][j])dfs(h, visited, i - 1, j,h[i][j])dfs(h, visited, i, j + 1,h[i][j])dfs(h, visited, i, j - 1,h[i][j])DEFINE static voidmain(String[] args)DEFINE [][] h ={{1,2,2,3,5},{3,2,3,4,4},{2,4,5,3,1},{6,7,1,4,5},{5,1,1,2,4}}System.out.println(pacificAtlantic(h))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/29

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