Talentd
FleetCode
Make and follow sheets.Sign in

Create Grid With Exactly One Path solution and explanation

Easy4 min read85.9% acceptanceUpdated 27 Jul 2026
3963. Create Grid With Exactly One Path (Leetcode Easy)Programming Live with Larry · 6:39 · 297 viewsWatch on YouTube
4 more videos on this problem
  1. 3963. Create Grid With Exactly One Path (Leetcode Easy)Programming Live with Larry · 6:39 · 297 views
  2. Leetcode 3963 | Create Grid With Exactly One Path | Easy | Simple Observation | Biweekly Contest 185Vijay Algorithms · 8:47 · 127 views
  3. Q1. Create Grid With Exactly One Path | Biweekly Contest 185 | LeetCodeaniketdevlp · 5:25 · 64 views
  4. Create Grid With Exactly One Path| Leetcode bi-weekly contest 185 | #3963UMANG AGRAWAL · 5:51 · 49 views
  5. LeetCode 3963: Create Grid With Exactly One Path | Most Easy C++ SolutionAeXel · 11:07 · 35 views

The problem

You are given two integers m and n, representing the number of rows and columns of a grid.

Construct any m x n grid consisting only of the characters '.' and '#', where:

  • '.' represents a free cell.
  • '#' represents an obstacle cell.

A valid path is a sequence of free cells that:

  • Starts at the top-left cell (0, 0).
  • Ends at the bottom-right cell (m - 1, n - 1).
  • Moves only:
    • Right, from (i, j) to (i, j + 1), or
    • Down, from (i, j) to (i + 1, j).

Return any grid such that there is exactly one valid path from the top-left cell to the bottom-right cell.

Example 1:

Input: m = 2, n = 3

Output: ["..#","#.."]

Explanation:

The only valid path is: (0,0) → (0,1) → (1,1) → (1,2)

Example 2:

Input: m = 3, n = 3

Output: ["..#","#..","##."]

Explanation:

The only valid path is: (0,0) → (0,1) → (1,1) → (1,2) → (2,2)

Example 3:

Input: m = 1, n = 4

Output: ["...."]

Explanation:

The only valid path is: (0,0) → (0,1) → (0,2) → (0,3)

Constraints:

  • 1 <= m, n <= 25

Approach overview

Problem Overview: You need to construct an m x n grid such that there is exactly one valid path from the top-left cell to the bottom-right cell. Movement is typically restricted to right or down, so the grid must block all alternative routes while keeping one continuous path.

Approach 1: Brute Force Grid Search (Backtracking) (Time: exponential, Space: O(m*n))

One theoretical approach is to generate different grid configurations of open and blocked cells and run a path counting algorithm such as DFS or DP to verify whether exactly one path exists. For every configuration, you run a traversal from (0,0) and count ways to reach (m-1,n-1). This quickly becomes infeasible because the number of possible grids grows exponentially with m*n. It mainly serves as a conceptual baseline showing the requirement: all alternative routes must be blocked.

Approach 2: Deterministic Grid Construction (Time: O(m*n), Space: O(1))

The practical solution is to construct the grid so only a single path is physically possible. A simple pattern is to keep the entire first row open and the entire last column open, while blocking all other cells. Starting from (0,0), the only possible movement is to go right across the first row until the last column, then move down to the bottom-right corner. Any attempt to move down earlier hits a blocked cell, eliminating alternative paths.

This guarantees exactly one valid route while keeping the implementation trivial. You initialize the grid, mark cells along the chosen path as passable, and block the rest. The algorithm only iterates through the grid once to assign values, so the runtime is O(m*n) with constant extra memory.

Conceptually, the problem relates to counting paths in a grid, commonly solved using dynamic programming. Instead of computing the number of paths, you design the grid so the count becomes exactly one. The construction also resembles a simple greedy strategy where you enforce a single deterministic route through a matrix.

Recommended for interviews: The deterministic construction approach. Interviewers expect you to recognize that multiple paths arise from branching choices. By blocking every branch except one straight route, you guarantee a unique path with a very simple O(m*n) construction. Mentioning brute force or DP path counting briefly shows understanding of the underlying grid path problem, but the direct construction demonstrates stronger problem-solving instincts.

Solution

We construct the grid as follows:

  • First, construct a grid filled entirely with #.
  • Set all elements in the first row to ..
  • Set all elements in the last column to ..
  • Return the constructed grid.

The time complexity is O(m times n), and the space complexity is O(m times n). Here, m and n are the number of rows and columns in the grid, respectively.

class Solution:
    def createGrid(self, m: int, n: int) -> list[str]:
        g = [["#"] * n for _ in range(m)]
        g[0] = ["."] * n
        for i in range(m):
            g[i][-1] = "."
        return ["".join(row) for row in g]
class Solution {
    public String[] createGrid(int m, int n) {
        char[][] g = new char[m][n];
        for (int i = 0; i < m; i++) {
            Arrays.fill(g[i], '#');
        }

        Arrays.fill(g[0], '.');

        for (int i = 0; i < m; i++) {
            g[i][n - 1] = '.';
        }

        String[] ans = new String[m];
        for (int i = 0; i < m; i++) {
            ans[i] = new String(g[i]);
        }
        return ans;
    }
}
class Solution {
public:
    vector<string> createGrid(int m, int n) {
        vector<string> g(m, string(n, '#'));

        g[0] = string(n, '.');

        for (int i = 0; i < m; i++) {
            g[i][n - 1] = '.';
        }

        return g;
    }
};
function createGrid(m: number, n: number): string[] {
    const g: string[][] = Array.from({ length: m }, () => Array(n).fill('#'));

    g[0].fill('.');

    for (let i = 0; i < m; i++) {
        g[i][n - 1] = '.';
    }

    return g.map(row => row.join(''));
}
func createGrid(m int, n int) []string {
    g := make([][]byte, m)
    for i := range g {
        g[i] = make([]byte, n)
        for j := range g[i] {
            g[i][j] = '#'
        }
    }

    for j := 0; j < n; j++ {
        g[0][j] = '.'
    }

    for i := 0; i < m; i++ {
        g[i][n-1] = '.'
    }

    ans := make([]string, m)
    for i := range g {
        ans[i] = string(g[i])
    }
    return ans
}
Try this approach in the editor

Complexity analysis

ApproachTimeSpaceWhen to Use
Brute Force Grid Enumeration + DFS Path CountExponentialO(m*n)Conceptual understanding of how unique paths emerge
Dynamic Programming Path Counting (Validation)O(m*n)O(m*n)When verifying the number of paths in an existing grid
Deterministic Grid ConstructionO(m*n)O(1)Best approach to directly build a grid with exactly one path

Frequently asked questions

Is Create Grid With Exactly One Path easy or hard?

Create Grid With Exactly One Path is classified as an Easy problem. The key insight is recognizing that you do not need to compute paths at all. By constructing the grid so that only one route exists, the solution becomes a straightforward O(m*n) matrix initialization.

Create Grid With Exactly One Path Python/Java solution

The implementation initializes an m x n grid and marks cells along one deterministic route as open while the rest remain blocked. In Python or Java, this typically means filling the first row with passable cells, filling the last column, and assigning blocked values elsewhere.

How to solve Create Grid With Exactly One Path in O(n)?

The grid can be constructed directly without exploring paths. Mark a single continuous path from (0,0) to (m-1,n-1), for example by filling the first row and then the last column, and block every other cell. This ensures there is exactly one valid route while keeping the runtime proportional to the grid size.

What is the best approach for Create Grid With Exactly One Path?

The best approach is deterministic grid construction. You deliberately open cells along a single route, such as the entire first row followed by the last column, and block all other cells. This guarantees exactly one path from the start to the destination and runs in O(m*n) time with constant extra space.

Is Create Grid With Exactly One Path asked at Google/Amazon/Meta?

Grid path construction and unique path counting problems frequently appear in interviews at companies like Google, Amazon, and Meta. Variants usually involve dynamic programming or matrix traversal. This specific problem tests whether you recognize that controlling grid structure can force a unique path.

What data structure is used in Create Grid With Exactly One Path?

The primary data structure is a 2D matrix representing the grid. The algorithm simply fills cells to define a valid route and block alternative moves. In related problems, matrices are often combined with dynamic programming tables or DFS traversal.

What is the time complexity of Create Grid With Exactly One Path?

The optimal construction solution runs in O(m*n) time because each grid cell may be initialized once. The algorithm only assigns values to cells and does not require expensive searches or path enumeration. Extra space usage remains O(1) aside from the output grid.

Comments

Now write it yourselfClose this page and solve Create Grid With Exactly One Path in the editor, without looking.
Practise Create Grid With Exactly One Path