Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Maximum Cluster in 2D Array

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Maximum Cluster in 2D Array. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Find the largest cluster detection in a 2D array.

Treat every nonzero cell as part of a cluster. Two cells belong to the same cluster when they are connected horizontally or vertically, not diagonally. Return the number of cells in the largest cluster.

Input: A rectangular 2D list of integers named grid.

Output: An integer representing the largest cluster size. Return 0 for an empty grid or a grid containing only zeros.

Examples:

  • grid = [[1, 1, 0], [0, 1, 0], [1, 0, 1]] returns 3 because the upper-left cluster contains three cells.
  • grid = [[1, 0], [0, 1]] returns 1 because diagonal cells are not connected.

Constraints: The grid is rectangular, contains at most 2,500 cells, and each cell is an integer.

Constraints

  • The grid is rectangular.
  • 0 <= len(grid) <= 2,500
  • Each row has the same number of columns.
  • Each cell is an integer.
  • A nonzero value belongs to a cluster, and zero represents an inactive cell.

Function Signature

def largest_cluster(grid):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output