LeetCode 778 Swim in Rising Water - Example and Complexity Analysis

Walkthrough and analysis

Trace [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]].

Sort cells by elevation: (0,0)=0, (0,1)=1, (0,2)=2, ...

Add cells in order. After adding cell with value 16 at (2,4):

  • Path exists: 0→1→2→3→4→5→6→7→8→9→10→11→12→13→14→15→16 forms a connected path from (0,0) to (4,4).

Answer: 16.

Binary search approach: O(n2log(n2)α(n2))O(n^2 \log(n^2) \cdot \alpha(n^2)). Sort-and-union approach: O(n2log(n2))O(n^2 \log(n^2)) for sorting, O(n2α(n2))O(n^2 \cdot \alpha(n^2)) for unions. Space: O(n2)O(n^2).