← Capgemini bank

Capgemini · Question 61 · Graphs

Pacific Atlantic Water Flow

GraphsC++code⏱ 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 1Branches 2Returns 1source · C++
Scroll sideways for wide charts — the view follows the active step.
yesno↻ repeatSTARTinclude <iostream>include <vector>using namespace stdDEFINEdfs(vector<vector<int>>&heights…DEFINE i, int j, int prev)DEFINE m = heights.size(),n = heights[0].size()if (i < 0 || i >= m ||j < 0 || j >= n ||visited[i][j] ||heights[i][j] < prev)returnvisited[i][j] = truedfs(heights, visited, i +1, j, heights[i][j])dfs(heights, visited, i -1, j, heights[i][j])dfs(heights, visited, i, j+ 1, heights[i][j])dfs(heights, visited, i, j- 1, heights[i][j])vector<vector<int>>pacificAtlantic(vector<vector<int>>&heights)DEFINE main()vector<vector<int>> 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}}auto r = pacificAtlantic(h)cout << "["for (size_t i = 0; i <r.size(); ++i)if (i) cout << ", "cout << "[" << r[i][0] <<", " << r[i][1] << "]"cout << "]" << endlRETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/24

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