Daily iOS
CS fundamentals and algorithms

Connected components, recursion limits

An image mask comes as an N×M grid where 1 is foreground and 0 is background. How would you write a function that returns an array with the size of each blob of 1s connected up, down, left, and right? Assume you're processing a 4000×3000 mask on an iPhone.

How would an interviewer hear this answer? You'll see whether they'd move on, dig in, or say no, and which sentences would trip you up. Your score doesn't change.
See the short answer

Scan the grid, and when you hit a 1, flood fill to count the blob, marking cells visited so they aren't counted again. O(N·M) time; extra space is the visited marks plus the queue's maximum frontier.

Share a question