BackeasyDynamic ProgrammingZomatoAccenture

Optimal Grid Path Engine 6 Solution

Problem Statement

You are tasked with optimizing the routing logic for a distributed sensor network. The network is modeled as a grid of size N x M, where each cell (i, j) contains a specific energy cost value. A signal must travel from the top-left corner (0, 0) to the bottom-right corner (N-1, M-1). At each step, the signal can only move right or down. However, the system imposes a strict bitmask constraint: the sum of the energy costs of all visited cells must be divisible by a given integer K. Your goal is to determine the minimum total energy cost required to reach the destination while satisfying this divisibility condition. If no such path exists, return -1.

The input consists of a 2D array 'grid' representing the energy costs, and an integer 'K' representing the modulus for the divisibility constraint. You must compute the minimum path sum such that the total sum modulo K equals 0. This problem requires a dynamic programming approach where the state tracks the current position and the current sum modulo K, effectively utilizing a bitmask-like state compression for the remainder values.

Example 1
Input
grid = [[1, 2], [3, 4]], K = 5
Output
10

Explanation: Possible paths from (0,0) to (1,1): 1. Right then Down: 1 -> 2 -> 4. Sum = 7. 7 % 5 = 2 (Invalid). 2. Down then Right: 1 -> 3 -> 4. Sum = 8. 8 % 5 = 3 (Invalid). Wait, let's re-evaluate. The problem asks for minimum sum divisible by K. Let's try a different grid for clarity in the example. Let's use grid = [[1, 2], [3, 4]], K = 7. Path 1: 1+2+4=7. 7%7=0. Valid. Cost 7. Path 2: 1+3+4=8. 8%7=1. Invalid. So output is 7. Let's stick to the first example but adjust K to make it work or provide a valid one. Let's use grid = [[1, 2], [3, 4]], K = 7. Output 7. Let's create a new example 1. Input: grid = [[1, 2], [3, 4]], K = 7 Output: 7 Explanation: Path (0,0)->(0,1)->(1,1) has sum 1+2+4=7. 7%7=0. Path (0,0)->(1,0)->(1,1) has sum 1+3+4=8. 8%7=1. Min valid sum is 7.

Example 2
Input
grid = [[1, 1], [1, 1]], K = 3
Output
4

Explanation: All paths have the same sum: 1+1+1=3. 3%3=0. The minimum sum is 3. Wait, 1+1+1 is 3. Is there a path with sum 4? No, all cells are 1. So sum is always 3. 3 is divisible by 3. Output 3. Let's adjust to make it more interesting. Input: grid = [[1, 2], [2, 1]], K = 4 Path 1: 1+2+1=4. 4%4=0. Valid. Path 2: 1+2+1=4. 4%4=0. Valid. Output 4.

Example 3
Input
grid = [[5, 1], [1, 5]], K = 3
Output
11

Explanation: Path 1: 5+1+5=11. 11%3=2. Invalid. Path 2: 5+1+5=11. 11%3=2. Invalid. No valid path? Let's check constraints. If no path, return -1. Let's try grid = [[1, 2], [3, 4]], K = 6. Path 1: 1+2+4=7. 7%6=1. Path 2: 1+3+4=8. 8%6=2. Output -1. Let's provide a valid one. Input: grid = [[2, 3], [4, 5]], K = 5 Path 1: 2+3+5=10. 10%5=0. Valid. Path 2: 2+4+5=11. 11%5=1. Invalid. Output 10.

Constraints

  • 1 <= grid.length <= 100
  • 1 <= grid[0].length <= 100
  • 1 <= grid[i][j] <= 100
  • 1 <= K <= 100
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Optimal Grid Path Engine 6 — Problem Statement & Solution Guide

Dynamic ProgrammingEasyBitmask DP
TimeO(N * M * 2^B)
|
SpaceO(M * 2^B)

Problem Description

You are tasked with optimizing the routing logic for a distributed sensor network. The network is modeled as a grid of size N x M, where each cell (i, j) contains a specific energy cost value. A signal must travel from the top-left corner (0, 0) to the bottom-right corner (N-1, M-1). At each step, the signal can only move right or down. However, the system imposes a strict bitmask constraint: the sum of the energy costs of all visited cells must be divisible by a given integer K. Your goal is to determine the minimum total energy cost required to reach the destination while satisfying this divisibility condition. If no such path exists, return -1.

The input consists of a 2D array 'grid' representing the energy costs, and an integer 'K' representing the modulus for the divisibility constraint. You must compute the minimum path sum such that the total sum modulo K equals 0. This problem requires a dynamic programming approach where the state tracks the current position and the current sum modulo K, effectively utilizing a bitmask-like state compression for the remainder values.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Optimal Grid Path Engine 6"

easy

WHY DOES IT MATTER?

The "grid DP with bitmask" pattern captures problems where a path’s feasibility depends on a cumulative property (e.g., permissions, resource usage) that can be encoded as bits. Recognizing this pattern lets you extend simple DP to handle combinatorial constraints without exponential blow‑up.

OPTIMIZATION CHALLENGE

The key insight is to treat the bitmask as a bounded state space (usually ≤ 2^B) and to prune impossible masks early. By using a rolling 2‑row array or in‑place updates, you reduce space from O(N*M*2^B) to O(M*2^B).

REAL-WORLD CONNECTION

Think of a packet traversing routers where each router adds a feature flag to the packet header; the packet must reach its destination without exceeding a security mask. The DP models the optimal routing cost while respecting the header constraints.

When coding, first implement the DP for a single mask to verify transition logic, then generalize to the full mask loop. Use a large sentinel (e.g., INF) and update only when the new mask is valid; this avoids subtle bugs with uninitialized states.

COMPLEXITY AT A GLANCE

⏱ Time:O(N * M * 2^B)
💾 Space:O(M * 2^B)

Core Theory — Why This Approach?

The problem is a classic grid DP where the state must capture both the position (i, j) and the accumulated bitmask of the path taken so far. A naive recursion that explores every possible right/down sequence quickly explodes because there are C(N+M-2, N-1) paths, which is exponential for large N and M. By recognizing optimal substructure— the best way to reach (i, j) with a particular mask depends only on the best ways to reach its two predecessors (i‑1, j) and (i, j‑1) with the same mask updated by the current cell’s value— we can transform the exponential search into a polynomial DP. The optimal paradigm is a 2‑dimensional DP augmented with a third dimension for the bitmask, often compressed using rolling arrays to keep space linear in the mask size.

Interview Questions on This Problem

Q1How would you modify the DP if the bitmask constraint required the cumulative OR of visited cells to never exceed a given limit K?

Maintain DP[i][j][mask] only for masks where (mask | cellValue) <= K; transition by OR-ing the current cell value with the predecessor mask and discard states that violate the limit. The answer is the minimum cost among DP[N-1][M-1][mask] for all valid masks.

Q2Explain why a BFS with a priority queue (Dijkstra) can also solve this problem and compare its complexity to the DP solution.

Each state (i, j, mask) can be treated as a node with edge weight equal to the next cell’s cost. Dijkstra explores states in order of increasing total cost, guaranteeing the optimal path. Its time complexity is O(N*M*2^B log(N*M*2^B)), where B is the number of bits, which is comparable to DP but adds a log factor; DP is usually faster because it processes states in a deterministic grid order.

Q3In a distributed sensor network, how would you parallelize the DP computation across multiple machines?

Partition the grid into diagonal wavefronts; each wavefront can be computed concurrently because all dependencies lie in the previous wavefront. Use a barrier after each diagonal and share the DP frontier (position, mask, cost) across machines, reducing overall wall‑clock time while preserving correctness.

Examples

Example 1

Input

grid = [[1, 2], [3, 4]], K = 5

Output

10

Explanation: Possible paths from (0,0) to (1,1): 1. Right then Down: 1 -> 2 -> 4. Sum = 7. 7 % 5 = 2 (Invalid). 2. Down then Right: 1 -> 3 -> 4. Sum = 8. 8 % 5 = 3 (Invalid). Wait, let's re-evaluate. The problem asks for minimum sum divisible by K. Let's try a different grid for clarity in the example. Let's use grid = [[1, 2], [3, 4]], K = 7. Path 1: 1+2+4=7. 7%7=0. Valid. Cost 7. Path 2: 1+3+4=8. 8%7=1. Invalid. So output is 7. Let's stick to the first example but adjust K to make it work or provide a valid one. Let's use grid = [[1, 2], [3, 4]], K = 7. Output 7. Let's create a new example 1. Input: grid = [[1, 2], [3, 4]], K = 7 Output: 7 Explanation: Path (0,0)->(0,1)->(1,1) has sum 1+2+4=7. 7%7=0. Path (0,0)->(1,0)->(1,1) has sum 1+3+4=8. 8%7=1. Min valid sum is 7.

Example 2

Input

grid = [[1, 1], [1, 1]], K = 3

Output

4

Explanation: All paths have the same sum: 1+1+1=3. 3%3=0. The minimum sum is 3. Wait, 1+1+1 is 3. Is there a path with sum 4? No, all cells are 1. So sum is always 3. 3 is divisible by 3. Output 3. Let's adjust to make it more interesting. Input: grid = [[1, 2], [2, 1]], K = 4 Path 1: 1+2+1=4. 4%4=0. Valid. Path 2: 1+2+1=4. 4%4=0. Valid. Output 4.

Example 3

Input

grid = [[5, 1], [1, 5]], K = 3

Output

11

Explanation: Path 1: 5+1+5=11. 11%3=2. Invalid. Path 2: 5+1+5=11. 11%3=2. Invalid. No valid path? Let's check constraints. If no path, return -1. Let's try grid = [[1, 2], [3, 4]], K = 6. Path 1: 1+2+4=7. 7%6=1. Path 2: 1+3+4=8. 8%6=2. Output -1. Let's provide a valid one. Input: grid = [[2, 3], [4, 5]], K = 5 Path 1: 2+3+5=10. 10%5=0. Valid. Path 2: 2+4+5=11. 11%5=1. Invalid. Output 10.

Constraints

  • 1 <= grid.length <= 100
  • 1 <= grid[0].length <= 100
  • 1 <= grid[i][j] <= 100
  • 1 <= K <= 100

Optimal Approach & Strategy

Use dynamic programming with a three‑dimensional state (row, column, mask) and roll the DP over rows to achieve linear space.

Brute Force Approach

Recursively explore every right/down sequence, accumulating cost and mask, and keep the minimum cost among valid paths.

Verified Code Solutions

JavaScript Solution
Time: O(N * M * 2^B)
function solution(nums) {
   let n = nums.length;
   let dp = new Array(1 << n).fill(0);
   dp[1] = nums[0];
   for (let i = 2; i < (1 << n); i++) {
       let j = i & -i;
       dp[i] = Math.max(dp[i ^ j] + nums[j - 1], dp[i - 1]);
   }
   let maxSum = 0;
   for (let i = 0; i < n; i++) {
       for (let j = i; j < n; j++) {
           let pathSum = 0;
           for (let k = i; k <= j; k++) {
               pathSum += nums[k];
           }
           maxSum = Math.max(maxSum, pathSum);
       }
   }
   return maxSum;
}

Asked in Top Tech Interviews

ZomatoAccenture

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.