Regions Cut by Slashes solution explained
Regions Cut by Slashes gives an n by n grid where each cell is empty or holds a diagonal wall, / or \, and asks how many separate regions the walls cut the whole square into. Split every cell into four triangles, join the triangles a cell's wall does not separate, join touching triangles of neighbouring cells, and count the groups with union-find. That runs in O(n² α(n²)) time; scaling each cell up to a 3 by 3 block of pixels and flood filling also works in O(n²).
By Evin JohnPublished 9 min read
The problem in plain words
A square is divided into n by n unit cells. Each cell contains one character: a space for an empty cell, a forward slash / for a wall running from the cell's bottom-left corner to its top-right corner, or a backslash \ for a wall from top-left to bottom-right. Walls are thin lines that nothing can cross. Count the regions: the separate areas of the square that are connected without crossing a wall. The input is a list of n strings of length n.
| Rows | Regions | Why |
|---|---|---|
| / | 2 | One wall from corner to corner splits a single cell in two |
| \\ and \\ | 4 | The backslashes on the main diagonal form one long wall, splitting the square in half. Each of the other two cuts off a corner triangle |
| /_ and _/ | 3 | Each slash cuts off its own small corner, leaving one big middle region |
| \/ and /_ | 3 | The three walls meet at the center point. Together they cut off one triangle along the top edge and another along the left edge |
| _/_, /_\ and _\_ | 2 | Two slashes join into a wall from the left edge to the top edge. The two backslashes each touch the border at only one end, so they cut nothing off |
| __ and __ | 1 | No walls, one region |
The last row with walls is the instructive one. A wall only separates regions if it forms a closed barrier with other walls or the border. A wall segment hanging into open space, attached at one end, divides nothing.
What the interviewer is checking
Few candidates have a ready template for diagonal walls, so the interviewer sees how you turn an odd geometry into something you can search. They want a clear model of a cell, either triangles or pixels, and a reason why the model is faithful. The common follow-up is "why three pixels and not two?", and the common bug is mixing up which triangles each slash separates. Escaping the backslash correctly in your language is a small but real part of getting it right.
First approach: draw it in pixels and flood fill
Draw each cell as a 3 by 3 block of pixels. A / marks the three pixels on the block's anti-diagonal as wall, and a \ marks the main diagonal. Now count connected groups of open pixels, moving only up, down, left and right. A diagonal line of wall pixels blocks four-way movement completely, so regions in the picture match regions in the grid. With 2 by 2 blocks the picture is too coarse. The gap between two parallel slashes in neighbouring cells turns into a diagonal chain of single pixels that four-way movement cannot follow, so one region is split in two. The 2 x 2 grid with an empty top row and // underneath has 2 regions, yet 2 x 2 pixels count 3.
def regions_by_pixels(grid):
n = len(grid)
size = 3 * n
wall = [[False] * size for _ in range(size)]
for r, row in enumerate(grid):
for c, ch in enumerate(row):
for k in range(3):
if ch == "/":
wall[3 * r + k][3 * c + 2 - k] = True
elif ch == "\\":
wall[3 * r + k][3 * c + k] = True
regions = 0
for i in range(size):
for j in range(size):
if wall[i][j]:
continue
regions += 1
wall[i][j] = True # reuse the grid as the visited mark
stack = [(i, j)]
while stack:
a, b = stack.pop()
for x, y in ((a + 1, b), (a - 1, b), (a, b + 1), (a, b - 1)):
if 0 <= x < size and 0 <= y < size and not wall[x][y]:
wall[x][y] = True
stack.append((x, y))
return regionsThis is simple to reason about and already O(n²), with a constant factor of 9. Its weakness is memory: 9n² booleans. For an interview it is a perfectly good answer, and many interviewers accept it as the main solution.
Optimal model: four triangles per cell with union-find
Cut each cell along both of its diagonals into four triangles: top, right, bottom and left. A / wall separates top-and-left from right-and-bottom, so join top with left and right with bottom. A \ wall separates top-and-right from bottom-and-left, so join those pairs. An empty cell joins all four. Across cells, nothing ever blocks the shared edge, so a cell's bottom triangle always joins the top triangle of the cell below, and its right triangle joins the left triangle of the cell to its right. The number of union-find groups at the end is the number of regions.
def regions_by_triangles(grid):
n = len(grid)
parent = list(range(4 * n * n))
size = [1] * (4 * n * n)
count = 4 * n * n
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def join(a, b):
nonlocal count
a, b = find(a), find(b)
if a == b:
return
if size[a] < size[b]:
a, b = b, a
parent[b] = a
size[a] += size[b]
count -= 1
for r, row in enumerate(grid):
for c, ch in enumerate(row):
base = 4 * (r * n + c)
top, right, bottom, left = base, base + 1, base + 2, base + 3
if ch == "/":
join(top, left)
join(right, bottom)
elif ch == "\\":
join(top, right)
join(bottom, left)
else:
join(top, right)
join(right, bottom)
join(bottom, left)
if r + 1 < n:
join(bottom, 4 * ((r + 1) * n + c)) # top of the cell below
if c + 1 < n:
join(right, 4 * (r * n + c + 1) + 3) # left of the cell to the right
return countfunction regionsBySlashes(grid) {
const n = grid.length;
const total = 4 * n * n;
const parent = new Int32Array(total);
for (let i = 0; i < total; i++) parent[i] = i;
let count = total;
const find = (x) => {
while (parent[x] !== x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
};
const join = (a, b) => {
a = find(a);
b = find(b);
if (a !== b) { parent[a] = b; count--; }
};
for (let r = 0; r < n; r++) {
for (let c = 0; c < n; c++) {
const base = 4 * (r * n + c); // top, right, bottom, left = base .. base + 3
const ch = grid[r][c];
if (ch === "/") {
join(base, base + 3);
join(base + 1, base + 2);
} else if (ch === "\\") {
join(base, base + 1);
join(base + 2, base + 3);
} else {
join(base, base + 1);
join(base + 1, base + 2);
join(base + 2, base + 3);
}
if (r + 1 < n) join(base + 2, 4 * ((r + 1) * n + c));
if (c + 1 < n) join(base + 1, 4 * (r * n + c + 1) + 3);
}
}
return count;
}In both languages a single backslash character is written as "\\" inside a string literal, because the backslash is the escape character. A lone backslash before the closing quote escapes the quote instead, which leaves the string unterminated, so it is worth saying out loud when you write it.
A third view: count closed loops
There is also a neat counting argument. Treat the (n + 1) by (n + 1) grid corners as points, and start with every border point already joined, since the border is one closed wall. Each slash joins two corner points. If the two points were already connected, this wall closes a new loop and adds exactly one region; otherwise it just extends a wall. Starting from 1 region, add one for every slash that closes a loop. It uses union-find on (n + 1)² points and is worth mentioning as an alternative once the main solution works.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| 3 x 3 pixels and flood fill | O(n²), constant about 9 | O(9n²) |
| Four triangles and union-find | O(n² α(n²)) | O(4n²) |
| Corner points and loop counting | O(n² α(n²)) | O((n + 1)²) |
Edge cases
- A 1 x 1 grid: 1 region if empty, 2 if it holds either slash.
- No walls anywhere: 1 region.
- Every cell a slash in the same direction: walls run in parallel diagonal lines and the count grows with n.
- Walls attached to the border at only one end: they do not create a region.
- Backslashes in the input: make sure the input is parsed as one character per cell, not two.
Common mistakes
- Using 2 x 2 pixels per cell, which splits a region wherever two parallel slashes sit side by side.
- Swapping the joins for / and \, which gives wrong counts on any grid that mixes them.
- Allowing diagonal moves in the pixel flood fill, which lets regions leak through the wall lines.
- Joining a cell's bottom triangle to the cell below's bottom instead of its top.
- Comparing with a single unescaped backslash in a string literal.
Follow-up questions
- Return the area of each region. In the triangle model, each triangle has area one quarter, so sum quarters per root.
- Cells can hold both slashes (an X). All four triangles stay separate inside that cell; only the cross-cell joins apply.
- Walls are added one at a time and you report the count after each. The corner-point loop counting handles this naturally, since each wall either closes a loop or does not.
How to explain it out loud
Fictional example
- Candidate
- Diagonal walls don't fit a normal grid search, so I'll split each cell into four triangles: top, right, bottom, left.
- Candidate
- A slash joins top with left and right with bottom. A backslash joins top with right and bottom with left. An empty cell joins all four.
- Interviewer
- What about between cells?
- Candidate
- Nothing blocks the shared edge, so bottom always joins the top of the cell below, and right joins the left of the next cell. Then I count union-find groups.
- Candidate
- The other option is three by three pixels and a flood fill. Two by two fails because the gap between parallel slashes gets too thin to walk through.
Related problems
Most Stones Removed with Same Row or Column is another problem where choosing the right union-find nodes is the whole trick. Similar String Groups counts components when edges must be discovered. For flood fill on an ordinary grid, start with Surrounded Regions or Max Area of Island.
Practicing it with Natively
Drawing the four triangles on paper before coding is what makes this problem manageable, and it is worth practicing until the joins come out right the first time. When you practice on a Mac or Windows PC, Natively can read a slash grid from a screenshot, suggest the triangle model or the 3 x 3 pixel version, and transcribe your mock explanation so you can review whether you justified the pixel size. The LeetCode practice helper page shows the routine.
Questions people ask
How do you solve Regions Cut by Slashes?
Split each cell into top, right, bottom and left triangles. Join the pairs a slash does not separate (all four for an empty cell), join touching triangles of neighbouring cells, and count union-find groups.
Why use 3 x 3 pixels instead of 2 x 2?
At 2 x 2 the gap between parallel slashes in neighbouring cells becomes a diagonal chain of single pixels, which four-way flood fill cannot cross, so regions get split. 3 x 3 leaves room to pass.
What is the time complexity of Regions Cut by Slashes?
O(n² α(n²)) with the triangle union-find and O(n²) with the pixel flood fill, both using O(n²) space.
How do you write a backslash in the code?
As an escaped backslash inside the string literal, written with two backslash characters in Python and JavaScript.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
