Skip to main content

Regions Cut By Slashes - Solution & Explanation

MediumArrayHash TableDepth-First SearchBreadth-First Search16 min readAsked at: Amazon, Microsoft, Meta +3
Practice this problem

Problem Statement

An n x n grid is composed of 1 x 1 squares where each 1 x 1 square consists of a '/', '\', or blank space ' '. These characters divide the square into contiguous regions.

Given the grid grid represented as a string array, return the number of regions.

Note that backslash characters are escaped, so a '\' is represented as '\\'.

 

Example 1:

Input: grid = [" /","/ "]
Output: 2

Example 2:

Input: grid = [" /","  "]
Output: 1

Example 3:

Input: grid = ["/\\","\\/"]
Output: 5
Explanation: Recall that because \ characters are escaped, "\\/" refers to \/, and "/\\" refers to /\.

 

Constraints:

  • n == grid.length == grid[i].length
  • 1 <= n <= 30
  • grid[i][j] is either '/', '\', or ' '.

Approach Overview

Problem Overview: You get an n x n grid where each cell contains '/', '\', or a blank space. These slashes divide the grid into multiple regions. The goal is to count how many disconnected regions are formed after all divisions.

Approach 1: Represent Each Grid Cell by a Subdivision into Smaller Triangles (DFS/BFS) (Time: O(n^2), Space: O(n^2))

Each grid cell can be split into four small triangles. A slash determines which triangles connect internally. For example, '/' connects the top-left and bottom-right boundaries differently than '\'. After subdivision, treat every triangle as a node in a graph. Use depth-first search or breadth-first search to explore connected triangles. Whenever you start a DFS from an unvisited triangle, you’ve discovered a new region. The grid effectively becomes 4 * n * n nodes, but traversal is still linear relative to the expanded graph.

This approach is intuitive because it converts the geometric problem into a standard graph traversal problem. If you’re comfortable with grid DFS problems, this method is straightforward to implement and easy to reason about.

Approach 2: Union-Find to Track Regions (Time: O(n^2 α(n)), Space: O(n^2))

Another way to model the grid is by splitting each cell into four subregions and connecting them using a Union-Find (Disjoint Set Union) structure. Inside each cell, union operations depend on the slash type. For example, a blank cell connects all four triangles, while '/' and '\' connect specific pairs. You also union triangles between neighboring cells so adjacent edges share the same component.

After processing the entire matrix, the number of unique DSU parents represents the number of regions. Path compression and union by rank keep operations nearly constant time. This approach avoids explicit graph traversal and works well when you prefer a connectivity model.

Recommended for interviews: The Union-Find solution is typically what interviewers expect because it demonstrates strong understanding of connected components and disjoint-set structures. The triangle subdivision with DFS shows good problem decomposition and is easier to visualize, but the DSU approach highlights algorithmic maturity and clean region counting.

Approach 1: Approach 1: Represent Each Grid Cell by a Subdivision into Smaller Triangles

In this approach, each 1x1 square is divided into four smaller triangles. The / and \ slashes correspond to boundaries between these triangles. We can represent these triangles using a graph and use DFS to count the number of connected components in this graph. Each connection between triangles denotes a passage within the same region.

The implementation involves creating a larger 3n x 3n grid where each grid cell is expanded into a 3x3 grid based on present slashes. We then perform a DFS for each unvisited triangle marking it visited, effectively counting the disconnected regions in the grid.

Code

Python

Java

Complexity

Time Complexity: O((n * 3) * (n * 3)), where n is the grid size as we traverse each 3x3 cell.
Space Complexity: O((n * 3) * (n * 3)) due to the graph representation.

Try this approach in the editor →

Approach 2: Approach 2: Union-Find to Track Regions

This approach uses the Union-Find data structure to manage and merge connected components. Each cell in the grid is broken into four triangles and represented as nodes in the DSU. Connectivity relationships are established and merged as per slashes present in the cell, and the number of disconnected regions is determined.

The C++ solution employs the Union-Find data structure to manage the four sub-triangles per cell. It efficiently merges them based on the presence of slashes to identify distinct regions. The number of unique sets determines the count of regions.

Code

C++

JavaScript

Complexity

Time Complexity: O(N^2 * α(N^2)), with α being a very slow-growing function (inverse Ackermann function), coming from the Union-Find operations.
Space Complexity: O(N^2) due to storing parent and rank structures for each cell division.

Try this approach in the editor →

Approach 3: Union-Find

Code

Python

Java

C++

Go

TypeScript

JavaScript

Try this approach in the editor →

Approach 4: DFS

Code

TypeScript

JavaScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Approach 1: Represent Each Grid Cell by a Subdivision into Smaller Triangles

Time Complexity: O((n * 3) * (n * 3)), where n is the grid size as we traverse each 3x3 cell.
Space Complexity: O((n * 3) * (n * 3)) due to the graph representation.

Approach 2: Union-Find to Track Regions

Time Complexity: O(N^2 * α(N^2)), with α being a very slow-growing function (inverse Ackermann function), coming from the Union-Find operations.
Space Complexity: O(N^2) due to storing parent and rank structures for each cell division.

Union-Find
DFS

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Grid Subdivision with DFS/BFSO(n^2)O(n^2)When you want a clear graph traversal model and easier visualization of regions
Union-Find (Disjoint Set Union)O(n^2 α(n))O(n^2)Preferred in interviews when solving connected component problems efficiently

Video Solution

Regions Cut By Slashes - Leetcode 959 - PythonNeetCodeIO20,781 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Regions Cut By Slashes easy or hard?
Regions Cut By Slashes is rated Medium difficulty on LeetCode with a high acceptance rate around 77%. The challenge lies in modeling the grid correctly rather than implementing complex algorithms. Once the cell subdivision idea or DSU mapping is clear, the implementation becomes straightforward.
How to solve Regions Cut By Slashes in O(n^2)?
Split each grid cell into four triangles and treat them as nodes in a graph. Connect triangles inside the cell depending on whether the character is '/', '\\', or space. Then connect boundary triangles with adjacent cells and run DFS/BFS to count connected components. This traversal visits each triangle once, giving O(n^2) time complexity.
Regions Cut By Slashes Python or Java solution
Python and Java implementations usually follow the triangle subdivision model. Each cell is expanded into four nodes, stored in arrays or adjacency relationships, and explored with DFS/BFS. Alternatively, a DSU structure unions triangles and counts unique parents after processing the grid.
What is the best approach for Regions Cut By Slashes?
Union-Find with cell subdivision into four triangles is the most common optimal approach. Each triangle becomes a node, and union operations connect triangles inside the cell and with neighboring cells. After processing the grid, the number of disjoint sets equals the number of regions. Time complexity is O(n^2 α(n)) with near-constant DSU operations.
Is Regions Cut By Slashes asked at Google/Amazon/Meta?
Grid connectivity and Union-Find problems like Regions Cut By Slashes appear frequently in interviews at companies such as Google, Amazon, and Meta. The problem tests graph modeling, connected components, and DSU implementation skills, which are common patterns in system-level algorithm interviews.
What data structure is used in Regions Cut By Slashes?
Two main data structures are used: graph traversal structures (for DFS or BFS) and Disjoint Set Union (Union-Find). The grid is typically modeled as four subcells per grid cell, and either traversal or DSU tracks connectivity between these regions.
What is the time complexity of Regions Cut By Slashes?
Both common solutions run in O(n^2) time because each grid cell is processed a constant number of times. The DFS/BFS subdivision approach explores up to 4*n*n nodes, while the Union-Find approach performs a constant number of union operations per cell. DSU operations add an inverse Ackermann factor α(n), which is effectively constant.

Ready to solve this problem?

Practice Regions Cut By Slashes with our built-in code editor and test cases.

Practice on FleetCode