PracHub
QuestionsCoachesLearningGuidesInterview Prep

Quick Overview

This question evaluates skills in graph traversal and grid connectivity detection, testing competency in reasoning about adjacency, state management, and edge-case handling such as empty grids and the exclusion of diagonal connections.

  • hard
  • Generalmotors
  • Coding & Algorithms
  • Machine Learning Engineer

Count Islands in a Grid

Company: Generalmotors

Role: Machine Learning Engineer

Category: Coding & Algorithms

Difficulty: hard

Interview Round: Technical Screen

Given an `m x n` grid where each cell is either land (`1`) or water (`0`), return the number of islands. An island is a group of land cells connected only horizontally or vertically. Diagonal connections do not count as connected. Implement a function such as: ```python def count_islands(grid: list[list[int]]) -> int: pass ``` Requirements: - The grid may be empty. - You may mutate the grid if you document that choice, or use a separate visited structure. - Write test cases that would catch common bugs, especially incorrectly treating diagonal land cells as connected.

Quick Answer: This question evaluates skills in graph traversal and grid connectivity detection, testing competency in reasoning about adjacency, state management, and edge-case handling such as empty grids and the exclusion of diagonal connections.

Return the number of 4-directionally connected land components.

Constraints

  • grid contains 0 water and 1 land

Examples

Input: ([[1, 1, 0], [0, 1, 0], [1, 0, 1]],)

Expected Output: 3

Explanation: Diagonal land is not connected.

Input: ([],)

Expected Output: 0

Explanation: Empty grid.

Input: ([[0, 0]],)

Expected Output: 0

Explanation: No land.

Input: ([[1, 1], [1, 1]],)

Expected Output: 1

Explanation: One island.

Hints

  1. BFS or DFS from each unvisited land cell.
Last updated: Jun 27, 2026

Loading coding console...

PracHub

Master your tech interviews with 8,000+ real questions from top companies.

Product

  • Questions
  • Learning Tracks
  • Interview Guides
  • Resources
  • Premium
  • For Universities
  • Student Access

Browse

  • By Company
  • By Role
  • By Category
  • Topic Hubs
  • SQL Questions
  • AI Coding Questions
  • Compare Platforms
  • Discord Community

Support

  • support@prachub.com
  • (916) 541-4762

Legal

  • Privacy Policy
  • Terms of Service
  • About Us

© 2026 PracHub. All rights reserved.