Quick revision
The short answer
Recursive DFS makes one nested call per land cell it reaches, so on a 4,000 x 4,000 grid that is mostly land the recursion can go millions of calls deep, up to 16 million, while a default thread stack of about 512 KB to 1 MB holds only some tens of thousands of frames. The tests passed because their grids were small. The fix is to replace the call stack with an explicit one: an iterative BFS or DFS over an ArrayDeque, or better an int array of encoded positions r * cols + c, marking each cell visited when it is pushed. Union-find with path compression and union by rank is another near-linear option. Raising -Xss only hides the problem and costs memory per thread.
What to remember
In this answer, we saw that the recursive island counter is correct but keeps one stack frame per pending cell, so on a mostly-land 4,000 x 4,000 grid its depth can reach millions while a default thread stack holds only tens of thousands of frames. Moving the pending cells to an explicit stack or queue on the heap, encoding each cell as r * cols + c and marking it visited when pushed, keeps the same algorithm without the depth limit. Union-find with path compression and union by rank is a near-linear alternative that also handles cells added one at a time, while raising -Xss only moves the limit.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Recursive DFS makes one nested call per land cell it reaches, so on a 4,000 x 4,000 grid that is mostly land the recursion can go millions of calls deep, up to 16 million, while a default thread stack of about 512 KB to 1 MB holds only some tens of thousands of frames. The tests passed because their grids were small. The fix is to replace the call stack with an explicit one: an iterative BFS or DFS over an ArrayDeque, or better an int array of encoded positions r * cols + c, marking each cell visited when it is pushed. Union-find with path compression and union by rank is another near-linear option. Raising -Xss only hides the problem and costs memory per thread.
Why this question is asked
This is a common shape of production bug: an algorithm that is correct and has the right complexity, but whose memory use is in the wrong place. The heap can hold gigabytes, while each thread's stack is a small fixed area, so recursion depth becomes a hidden limit on input size. Interviewers ask it to see whether we can connect an error to how the JVM runs our code and rewrite without changing the algorithm's meaning. In this answer, we will recap the island counting algorithm, explain why the recursive version overflows on this input, rewrite it with an explicit stack, keep memory low by encoding coordinates, look at union-find as an alternative, and explain why a bigger stack is not a fix.
1A Quick Recap of Counting Islands
The grid holds '1' for land and '0' for water. An island is a group of land cells connected horizontally or vertically. To count islands, we scan every cell; when we find unvisited land, we count one island and then visit every land cell connected to it, marking them so they are not counted again. Visiting a connected region is a graph traversal, and depth-first search, DFS, is the usual choice.
It is correct and O(rows x cols) time: every cell is visited a constant number of times. The problem is not the time; it is where the bookkeeping of the search lives.
2Why It Overflows in Production
Each call to sink waits for its four nested calls, so the chain of calls that are still in progress grows as long as the path DFS has taken through the island. On a mostly-land grid, DFS tends to snake through the whole region before it can back up. In the worst case, the depth equals the number of land cells in the island: up to 16 million for a 4,000 x 4,000 grid.
Each of those calls needs a stack frame holding its parameters and return address, and each thread's stack has a fixed size. The default is around 512 KB to 1 MB on common platforms, depending on the operating system and JVM, so check yours. That holds on the order of ten thousand frames of this size, not millions. When the stack is full, the JVM throws StackOverflowError. The tests passed because a 50 x 50 grid has at most 2,500 cells, well under the limit. The production grid is 6,400 times larger.
So the algorithm is fine. What we need to change is where the to-do list of the search is stored: from the small call stack to the heap, which has room for it.
- Recursive DFSone stack frame per pending cell, on the thread stack
- Thread stackfixed size, about 0.5 to 1 MB: some 10^4 frames
- Explicit stack or queueone int per pending cell, on the heap
- Java heapgigabytes: 16 million ints is 64 MB
4 layers, from the top down. Step through them one at a time.
Moving the pending cells from the call stack to a heap array removes the depth limit.
3Rewriting With an Explicit Stack
We keep a stack of cells still to visit. When we pop a cell, we push its unvisited land neighbours. To keep memory low, we encode each cell as a single int, r * cols + c, instead of allocating an int[] pair for it, and we mark a cell visited at the moment we push it, so no cell is ever pushed twice.
Marking on push, not on pop, is what bounds the stack: each land cell enters at most once, so the stack never holds more entries than there are land cells, 16 million ints or 64 MB in the very worst case, and in practice far fewer. If we marked on pop, a cell could be pushed by several neighbours before it is processed, which wastes memory and time.
An ArrayDeque<Integer> would also work and reads more simply, but it boxes each position into an Integer object, about 16 bytes plus a reference instead of 4 bytes. On a 16-million-cell grid that difference is hundreds of megabytes of garbage. For the same reason the four directions live in two static arrays, DR and DC, so the loop creates no objects at all per cell. Using the stack gives DFS order; using the array as a queue gives BFS. Either visits the same cells, so the count is identical.
4Union-Find as an Alternative
Union-find, also called a disjoint set, keeps a parent index for every cell. We start with each land cell as its own set and count them, then for every pair of neighbouring land cells we union their sets, decreasing the count each time a union actually joins two different sets. With path compression, where find makes nodes point closer to their root, and union by rank, which hangs the shorter tree under the taller one, each operation costs nearly constant time, O(alpha(n)), where alpha is the very slowly growing inverse Ackermann function. The whole grid is O(m n alpha(m n)).
It needs an int[] parent of size rows x cols, and its real strength is that it handles changes: it is the natural choice when cells become land one at a time and we want the island count after each addition. Its find method should also be iterative, for the same stack reason.
5Why a Bigger Stack Is Not the Fix
We could start the JVM with -Xss64m, or create a Thread with a stackSize argument, and the error would go away for this grid. But the limit only moves: a larger grid fails again. -Xss applies to every thread the JVM creates, so a server with hundreds of threads reserves far more address space, and the Thread stackSize argument is only a hint that some platforms ignore. It also hides the real property of the code, that its memory use grows with the input on the stack. The explicit stack fixes the design.
6Follow-up questions
How would you count islands when cells are added one at a time?
I would use union-find. I keep a parent array for all cells, initially empty, and a count. When a cell becomes land, I make it its own set and add one to the count, then for each of its up to four land neighbours I union the two sets, and every union that joins two different roots decreases the count by one. With path compression and union by rank, each addition costs nearly constant time, so k additions cost about O(k), and we can report the count after each one. Re-running a full DFS after every addition would cost O(m n) each time.
How would you find this bug before production?
With a test that uses the largest realistic input, here a 4,000 x 4,000 grid of all land, which is cheap to generate. Property-based or size-scaling tests catch recursion-depth limits that ordinary unit tests with small fixtures never reach. A code review rule helps too: any recursion whose depth depends on input size needs a bound or an iterative version.
7Conclusion
In this answer, we saw that the recursive island counter is correct but keeps one stack frame per pending cell, so on a mostly-land 4,000 x 4,000 grid its depth can reach millions while a default thread stack holds only tens of thousands of frames. Moving the pending cells to an explicit stack or queue on the heap, encoding each cell as r * cols + c and marking it visited when pushed, keeps the same algorithm without the depth limit. Union-find with path compression and union by rank is a near-linear alternative that also handles cells added one at a time, while raising -Xss only moves the limit.
Open with
The algorithm is fine, the problem is where it keeps its state. Recursive DFS makes one nested call per land cell along its path, and on a 4,000 by 4,000 grid that is mostly land, that path can include most of the 16 million cells.
Then, if they want more
Each call needs a stack frame, and a thread stack is fixed, typically around half a megabyte to a megabyte, which holds something like ten thousand frames of this size. The tests used small grids, so they never got near the limit. The fix is to keep the to-do list on the heap.
I would use an explicit stack, an int array that grows when needed, and encode each cell as row times cols plus column, so I do not allocate an int array or box an Integer per cell. When I find unvisited land, I count an island, mark the cell and push it.
Then I pop cells and push their unvisited land neighbours, marking them when I push, not when I pop, so each cell enters the stack at most once and the stack never exceeds the number of land cells. Using it as a queue gives BFS instead, with the same result.
Union-find with path compression and union by rank is another option, nearly linear, and it is the right tool if cells are added one at a time. What I would not do is raise -Xss. That just moves the limit to a bigger grid and costs memory in every thread.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A method counts islands of '1' cells in a char[][] grid with recursive DFS. It passes...": https://scrivio-interview-library.netlify.app/java/coding-problems/8557c61e73/