Bird
Raised Fist0
Interview Prepdp-grid-intervalshardGoogleAmazonFacebook

Cherry Pickup (Two Paths Simultaneously)

Choose your preparation mode4 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
📋
Problem

Imagine two friends starting at the top-left corner of a grid, each trying to collect as many cherries as possible while moving to the bottom-right corner simultaneously, but they cannot pick the same cherry twice.

Given an n x n grid filled with cherries (represented by 1), empty cells (0), and thorns (-1), two players start at (0,0) and move to (n-1,n-1) simultaneously. Each can only move right or down. They collect cherries on their paths, but if both land on the same cell, the cherry is counted only once. Return the maximum number of cherries both can collect together. If no valid path exists, return 0.

1 ≤ n ≤ 50grid[i][j] ∈ {-1, 0, 1}Both players start at (0,0) and end at (n-1,n-1)Players can only move right or down
Edge cases: Grid with all -1 except start and end → output 0Grid with no cherries → output 0Grid where one path is blocked forcing zero cherries
</>
IDE
def cherryPickup(grid: List[List[int]]) -> int:public int cherryPickup(int[][] grid)int cherryPickup(vector<vector<int>>& grid)function cherryPickup(grid)
def cherryPickup(grid):
    # Write your solution here
    pass
class Solution {
    public int cherryPickup(int[][] grid) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int cherryPickup(vector<vector<int>>& grid) {
    // Write your solution here
    return 0;
}
function cherryPickup(grid) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: -1 or negative valuesReturning negative infinity or invalid states instead of 0 when no path exists.Return max(ans, 0) at the end to ensure non-negative output.
Wrong: Overcounted cherries (greater than correct max)Double counting cherries when both players land on the same cell.Add cherries from second player only if positions differ: if (r1 != r2 || c1 != c2).
Wrong: 0 when valid cherries existFailing to explore all valid paths or pruning too aggressively on blocked cells.Ensure DP explores all four possible moves and prunes only invalid states with -1.
Wrong: Timeout / TLEUsing pure recursion without memoization causing exponential time complexity.Implement memoization or bottom-up DP to reduce complexity to O(n^3).
Wrong: Incorrect output on single cell gridNot handling base case n=1 properly.Return grid[0][0] if not blocked, else 0.
Test Cases
t1_01basic
Input{"grid":[[0,1,-1],[1,0,-1],[1,1,1]]}
Expected5

One optimal path collects cherries at positions (0,1), (1,0), (2,0), (2,1), and (2,2). Both players coordinate to maximize total cherries without double counting.

t1_02basic
Input{"grid":[[1,1,1],[1,-1,1],[1,1,1]]}
Expected7

Optimal paths collect cherries from most cells except the blocked cell (1,1). Total cherries collected is 7.

t2_01edge
Input{"grid":[[0]]}
Expected0

Single cell grid with no cherries; maximum cherries collected is 0.

t2_02edge
Input{"grid":[[0,0],[0,0]]}
Expected0

Grid with no cherries; maximum cherries collected is 0.

t2_03edge
Input{"grid":[[0,-1],[1,0]]}
Expected0

One path blocked by thorn (-1) forcing no valid path; result is 0.

t3_01corner
Input{"grid":[[1,0,0],[0,1,0],[0,0,1]]}
Expected3

Cherries only on diagonal; both players must pick cherries on diagonal cells without overlap counting twice.

t3_02corner
Input{"grid":[[1,1,1,1],[1,-1,-1,1],[1,-1,-1,1],[1,1,1,1]]}
Expected10

Grid with blocked cells forcing detours; greedy approach picking local max cherries fails here.

t3_03corner
Input{"grid":[[1,1,1],[1,1,1],[1,1,1]]}
Expected9

Tests confusion between 0/1 and unbounded knapsack style counting; cherries can only be picked once per cell.

t4_01performance
Input{"grid":[[0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1],[1,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0],[0,1,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0],[0,0,1,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,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,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,1,0,0,1,0],[0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,1,0,0,1],[1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,1,0,0],[0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,1,0],[0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,1],[1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0]]}
⏱ Performance - must finish in 2000ms

Large grid with n=50; O(n^3) DP must complete within 2 seconds.

Practice

(1/5)
1. Consider the following Python code implementing the space-optimized DP solution for counting unique paths with obstacles. Given the input grid below, what is the value of the dp array after processing the second row (i=1)? Input grid: [[0,0,0], [0,1,0], [0,0,0]]
def uniquePathsWithObstacles(obstacleGrid):
    m, n = len(obstacleGrid), len(obstacleGrid[0])
    dp = [0]*n
    dp[0] = 1 if obstacleGrid[0][0] == 0 else 0
    for i in range(m):
        for j in range(n):
            if obstacleGrid[i][j] == 1:
                dp[j] = 0
            else:
                if j > 0:
                    dp[j] += dp[j-1]
    return dp[-1]
easy
A. [1, 1, 1]
B. [1, 1, 0]
C. [1, 0, 0]
D. [1, 0, 1]

Solution

  1. Step 1: Initialize dp after first row (i=0)

    dp starts as [1,0,0]. After processing first row (all zeros), dp updates to [1,1,1].
  2. Step 2: Process second row (i=1)

    At j=0, obstacleGrid[1][0]=0, dp[0] remains 1.
    At j=1, obstacleGrid[1][1]=1 (obstacle), dp[1] set to 0.
    At j=2, obstacleGrid[1][2]=0, dp[2] += dp[1] -> dp[2] = 1 + 0 = 1.
    Resulting dp: [1, 0, 1]
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    dp correctly zeroes obstacle cell and accumulates paths [OK]
Hint: Obstacles zero dp cells, dp[j] accumulates from dp[j-1] [OK]
Common Mistakes:
  • Forgetting to zero dp[j] on obstacle
  • Mis-updating dp[j] before dp[j-1]
  • Confusing row and column indices
2. What is the time complexity of the space-optimized bottom-up DP solution for the Cheapest Flights Within K Stops problem, given n cities, E flights, and maximum K stops?
medium
A. O(K * E) because each iteration relaxes all edges up to K+1 times
B. O(n^3) due to nested loops over cities and stops
C. O(E * log n) similar to Dijkstra's algorithm
D. O(n * K^2) due to dynamic programming over stops and cities

Solution

  1. Step 1: Identify loops in the algorithm

    The outer loop runs K+1 times, and the inner loop iterates over all E flights to relax edges.
  2. Step 2: Calculate total complexity

    Each iteration processes E edges, so total time is O(K * E). No nested loops over n^2 or log factors appear.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Algorithm iterates over edges K+1 times [OK]
Hint: Outer loop K+1 times, inner loop over E edges [OK]
Common Mistakes:
  • Confusing E with n^2
  • Assuming Dijkstra complexity
  • Counting recursion stack space
3. What is the time complexity of the space-optimized bottom-up DP solution for the Maximal Square problem on an m x n matrix, and why might some candidates incorrectly think it is higher?
medium
A. O(m^3) because checking all squares requires nested loops
B. O(m * n * min(m,n)) because of checking all possible square sizes
C. O(m * n) because each cell is processed once with constant time updates
D. O(m + n) because only rows and columns are iterated separately

Solution

  1. Step 1: Identify loops in the code

    Two nested loops iterate over rows and columns, each cell processed once.
  2. Step 2: Understand DP update cost

    Each dp update is O(1), no nested checks for squares inside loops.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    DP avoids checking all squares explicitly [OK]
Hint: DP processes each cell once with constant work [OK]
Common Mistakes:
  • Confusing brute force with DP complexity
  • Assuming nested loops check all squares
  • Ignoring constant time DP updates
4. What is the time complexity of the bottom-up DP solution for the Triangle minimum path sum problem with n rows, and why?
medium
A. O(n^2) because each element in the triangle is processed once
B. O(2^n) because of the exponential number of paths
C. O(n) because each row is processed once
D. O(n^3) because of nested loops over rows and columns

Solution

  1. Step 1: Count total elements in triangle

    Triangle has 1 + 2 + ... + n = n(n+1)/2 elements, which is O(n^2).
  2. Step 2: Analyze loops

    Outer loop runs n times, inner loop runs up to n times per iteration, total O(n^2) operations.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Each element processed once in nested loops [OK]
Hint: Sum of rows is O(n^2), so time is O(n^2) [OK]
Common Mistakes:
  • Confusing number of rows with total elements
  • Assuming exponential complexity due to recursion
  • Overestimating complexity due to nested loops
5. What is the time complexity of the space-optimized bottom-up dynamic programming solution for the Unique Paths problem on an m x n grid?
medium
A. O(m^2 * n^2)
B. O(m + n)
C. O(m * n * min(m, n))
D. O(m * n)

Solution

  1. Step 1: Identify loops in the code

    The solution uses two nested loops: outer loop runs m-1 times, inner loop runs n-1 times.
  2. Step 2: Calculate total operations

    Total operations ≈ (m-1) * (n-1) -> O(m * n). No extra hidden loops or recursion stack.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Nested loops over m and n -> O(m*n) [OK]
Hint: Nested loops over m and n -> O(m*n) [OK]
Common Mistakes:
  • Confusing with recursion exponential time
  • Forgetting loops multiply complexity