Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #694: Number of Distinct Islands

In this guide, we solve Leetcode #694 Number of Distinct Islands in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

Quick Facts

  • Difficulty: Medium
  • Premium: Yes
  • Tags: Depth-First Search, Breadth-First Search, Union Find, Hash Table, Hash Function

Intuition

Fast membership checks and value lookups are the heart of this problem, which makes a hash map the natural choice.

By storing what we have already seen (or counts/indexes), we can answer the question in one pass without backtracking.

Approach

Scan the input once, using the map to detect when the condition is satisfied and to update state as you go.

This keeps the solution linear while remaining easy to explain in an interview setting.

Steps:

  • Initialize a hash map for seen items or counts.
  • Iterate through the input, querying/updating the map.
  • Return the first valid result or the final computed value.

Example

Input: grid = [[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]] Output: 1

Python Solution

class Solution: def numDistinctIslands(self, grid: List[List[int]]) -> int: def dfs(i: int, j: int, k: int): grid[i][j] = 0 path.append(str(k)) dirs = (-1, 0, 1, 0, -1) for h in range(1, 5): x, y = i + dirs[h - 1], j + dirs[h] if 0 <= x < m and 0 <= y < n and grid[x][y]: dfs(x, y, h) path.append(str(-k)) paths = set() path = [] m, n = len(grid), len(grid[0]) for i, row in enumerate(grid): for j, x in enumerate(row): if x: dfs(i, j, 0) paths.add("".join(path)) path.clear() return len(paths)

Complexity

The time complexity is O(n). The space complexity is O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy