Skip to main content

Create Grid With Exactly K Paths II - Solution & Explanation

HardPremiumFree on FleetCode4 min read
Practice this problem

Problem Statement

You are given an integer k.

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

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

The grid must contain at most 25 rows and at most 25 columns.

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), where m and n are the dimensions of your constructed grid.
  • 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 are exactly k valid paths from the top-left cell to the bottom-right cell. If no such grid exists, return an empty array.

 

Example 1:

Input: k = 2

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

Explanation:

The grid contains exactly 2 valid paths from (0, 0) to (2, 2):

  • (0, 0) → (0, 1) → (1, 1) → (1, 2) → (2, 2)
  • (0, 0) → (0, 1) → (1, 1) → (2, 1) → (2, 2)

Example 2:

Input: k = 3

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

Explanation:

​​​​​​​

The grid contains exactly 3 valid paths from (0, 0) to (2, 2):

  • (0, 0) → (0, 1) → (0, 2) → (1, 2) → (2, 2)
  • (0, 0) → (0, 1) → (1, 1) → (1, 2) → (2, 2)
  • (0, 0) → (0, 1) → (1, 1) → (2, 1) → (2, 2)

 

Constraints:​​​​​​​

  • 1 <= k <= 1000

Approach Overview

Problem Overview: You need to construct a grid where the number of valid paths from the start cell to the destination is exactly k. The challenge is not path traversal itself, but designing the grid so the path count matches the target precisely.

Approach 1: Brute Force Enumeration (Exponential Time, Exponential Space)

The most direct idea is to generate candidate grids and count all possible paths using DFS or backtracking. For each grid configuration, recursively move right or down and increment the count whenever you reach the destination. This works only for very small constraints because the number of grid states and path combinations grows exponentially. Time complexity is O(2^(m*n)) or worse depending on the search space, and space complexity is O(m*n) for recursion.

Approach 2: Dynamic Programming Path Counting (O(m*n) Time, O(m*n) Space)

A better strategy computes the number of paths for a fixed grid using dynamic programming. Define dp[r][c] as the number of ways to reach cell (r,c). Each value comes from the top and left neighbors. This approach efficiently validates whether a constructed grid produces exactly k paths. You typically combine this with incremental grid modification or state search. This is a standard application of dynamic programming and grid traversal.

Approach 3: Binary Construction / DAG Encoding (Optimal Construction)

The optimal solution treats the grid as a directed acyclic graph where each open cell contributes to the total number of reachable paths. The key insight is that path counts can represent powers of two, allowing you to encode any value of k through selective blocking or enabling of transitions. Instead of brute forcing layouts, you build a structured grid where each layer doubles the number of possible routes. Then you use the binary representation of k to activate only the required contributions. This reduces construction complexity dramatically and scales even for very large values of k.

Most accepted solutions use a compact construction with carefully placed walls and open cells. The implementation relies on graph traversal concepts and sometimes bit manipulation to map binary digits into path choices. Typical time complexity is O(log k) or O(n^2) depending on the grid size used for encoding, while space complexity remains O(n^2).

Recommended for interviews: Interviewers usually expect the constructive DP or binary encoding approach. Starting with brute force shows you understand how paths are counted, but the optimized construction demonstrates algorithmic reasoning and control over combinatorial growth. Focus on explaining how each grid layer contributes a deterministic number of paths and how binary decomposition guarantees an exact match for k.

Solutions for this problem are being prepared.

Try solving it yourself

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force EnumerationO(2^(m*n))O(m*n)Small grids or validating ideas during debugging
DP Path CountingO(m*n)O(m*n)When the grid is fixed and you only need path counts
Binary Grid ConstructionO(log k)O(n^2)General optimal solution for large k values
DAG-Based Layer ConstructionO(n^2)O(n^2)When deterministic path composition is required

Frequently Asked Questions

Is Create Grid With Exactly K Paths II easy or hard?
Create Grid With Exactly K Paths II is classified as Hard because the challenge is constructive reasoning rather than standard traversal. You must control the exact number of paths, which requires understanding DP state propagation and combinatorial encoding.
Create Grid With Exactly K Paths II Python/Java solution
Python solutions usually use lists and iterative grid construction, while Java implementations rely on arrays and explicit matrix initialization. Both versions follow the same DP or binary construction logic with O(log k) or O(n^2) complexity.
How to solve Create Grid With Exactly K Paths II in O(n)?
Most optimized solutions reduce the problem to controlled path generation using a layered DAG or binary grid encoding. Each layer doubles the number of available paths, allowing exact reconstruction of k using binary digits. The actual implementation complexity is commonly O(log k) or O(n^2).
What is the best approach for Create Grid With Exactly K Paths II?
The best approach uses constructive dynamic programming with binary decomposition. You design grid layers that contribute powers of two paths, then enable or disable transitions based on the binary representation of k. This avoids brute force enumeration and scales efficiently for large inputs.
Is Create Grid With Exactly K Paths II asked at Google/Amazon/Meta?
Constructive graph and dynamic programming problems similar to this appear in Google, Meta, and Amazon interview preparation sets. Interviewers use these problems to test combinatorial reasoning, DP transitions, and graph modeling skills.
What data structure is used in Create Grid With Exactly K Paths II?
The solution primarily uses a 2D grid combined with dynamic programming tables or graph-style adjacency reasoning. Some implementations also rely on bit manipulation to encode the contribution of each layer to the final path count.
What is the time complexity of Create Grid With Exactly K Paths II?
The optimal construction usually runs in O(log k) or O(n^2) time depending on the grid representation. Space complexity is typically O(n^2) because the grid itself must be stored. Brute force approaches are exponential and fail on large constraints.

Ready to solve this problem?

Practice Create Grid With Exactly K Paths II with our built-in code editor and test cases.

Practice on FleetCode