Detect a Cycle of Same-Colored Pixels in an Image
Last updated: November 29, 2026
Quick Overview
Given a grid of characters representing pixel colors, return True if there is a cycle of length four or more made of same-colored pixels connected horizontally or vertically, otherwise False.
0
0
0 solved
Given a grid of characters representing pixel colors, return True if there is a cycle of length four or more made of same-colored pixels connected horizontally or vertically, otherwise False.
A Google screen question about image regions, the kind of check a Photos or Lens preprocessing step might need. The interviewer checks for the union-find shortcut: add each same-color edge once, and a cycle exists exactly when an edge joins two pixels already in the same set.
What the Interviewer Expects
- Treats same-color neighboring pixels as graph edges
- Adds each undirected edge once by looking only right and down
- Reports a cycle when an edge joins two pixels already connected
- Explains why grid cycles always have length at least four
- Compares with DFS that tracks the parent cell
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Return the pixels on one cycle.
- What if diagonal adjacency also counts?
- How would you find the largest region that contains no cycle?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input: non-empty grid of characters.
- Pixels are adjacent if they share an edge.
- Output: whether a same-color cycle of length at least four exists....
High-Level Design
Union-find detects cycles in undirected graphs: when adding an edge whose endpoints are already connected, that edge closes a cycle. Scan cells and consider only the right and down neighbors so each e...