Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Medium Graphs Medium frequency Solution Available Practice Mode

Pacific Atlantic Water Flow LeetCode Solution

Tags: #Graph #DFS #BFS #Matrix

Approach Summary

Reverse DFS from ocean borders inward. Cells reachable from both oceans are the answer.

Practice Mode 2 Progressive Approaches

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Graphs Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Graphs pattern.

Framework: Graphs • Interview Prep: Tested at FAANG • Explore all Graphs problems & invariants →

How to Recognize This Pattern

  • Flow from borders inward (reverse thinking)
  • Two visited sets

Complexity Analysis

Time Complexity

O(m × n)

Space Complexity

O(m × n)

Tags

Graph DFS BFS Matrix

Frequently Asked Questions

What is the optimal time and space complexity for Pacific Atlantic Water Flow?
The optimal solution for Pacific Atlantic Water Flow achieves O(m × n) runtime complexity and requires O(m × n) auxiliary space. Time Complexity is O(M * N) where M is the number of rows and N is the number of columns. Each cell is visited at most once during the Pacific traversal and once during the Atlantic traversal. Space Complexity is O(M * N) to store the two reachability matrices and the recursion/queue call stack.
How do I identify that Pacific Atlantic Water Flow requires the Graphs pattern?
In technical interviews, look for key problem signals: Flow from borders inward (reverse thinking); Two visited sets. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Graphs strategy.
What critical edge cases must be handled in Pacific Atlantic Water Flow?
Essential edge cases to verify include: Single cell grid [[1]] — borders both oceans, returns [[0, 0]]; Flat plateau (all cells have identical height) — water flows freely everywhere, all cells return true; Strict strictly decreasing slope from center — water flows to oceans from borders and center, all cells reachable; Strict valley with elevated borders — center cells cannot reach borders. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Pacific Atlantic Water Flow?
Pacific Atlantic Water Flow is a Medium-difficulty question tagged with medium recurrence. It is actively asked in technical screening and onsite interview loops at Google, Facebook, Amazon.
Buy me a coffee
Daily Practice
0/0