Bird
Raised Fist0
Interview Prepgraphs-dfs-bfsmediumAmazonFacebookGoogle

01 Matrix

Choose your preparation mode4 modes available
</>
IDE
def updateMatrix(mat: list[list[int]]) -> list[list[int]]:public int[][] updateMatrix(int[][] mat)vector<vector<int>> updateMatrix(vector<vector<int>>& mat)function updateMatrix(mat)
def updateMatrix(mat: list[list[int]]) -> list[list[int]]:
    # Write your solution here
    pass
class Solution {
    public int[][] updateMatrix(int[][] mat) {
        // Write your solution here
        return new int[0][0];
    }
}
#include <vector>
using namespace std;

vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
    // Write your solution here
    return {};
}
function updateMatrix(mat) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: Distances too large or unchanged for some cellsUsing brute force approach checking each cell against all zeros, causing incorrect or incomplete updates.✅ Implement multi-source BFS starting from all zero cells simultaneously, updating neighbors with distance +1 only if smaller.
Wrong: All distances zero or unchanged from inputNot updating distances for cells with 1, or not initializing BFS queue with zero cells.✅ Initialize queue with all zero cells and set their distances to zero; update neighbors accordingly.
Wrong: Distances incorrect due to greedy approach picking first zero onlyUsing greedy method that assigns distance based on first zero found instead of shortest distance.✅ Use BFS to ensure shortest distance from any zero, not just first zero encountered.
Wrong: Distances incorrect due to treating problem as unbounded BFS or summing weights incorrectlyConfusing 0/1 BFS with unbounded BFS, leading to wrong distance calculations.✅ Use standard BFS with queue and update distances only if new distance is smaller.
✓
Test Cases
t1_01basic
Input{"mat":[[0,0,0],[0,1,0],[0,0,0]]}
Expected[[0,0,0],[0,1,0],[0,0,0]]

All 1s are adjacent to 0s, so their distance is 1.

t1_02basic
Input{"mat":[[0,1,1],[1,1,1],[1,1,0]]}
Expected[[0,1,2],[1,2,1],[1,1,0]]

Distances propagate from zeros at (0,0) and (2,2) to all cells.

t2_01edge
Input{"mat":[[0,0],[0,0]]}
Expected[[0,0],[0,0]]

All zeros, so distances remain zero.

t2_02edge
Input{"mat":[[1,1,1],[1,0,1],[1,1,1]]}
Expected[[2,1,2],[1,0,1],[2,1,2]]

Single zero in center, distances increase outward by Manhattan distance.

t2_03edge
Input{"mat":[[0]]}
Expected[[0]]

Single cell zero, distance is zero.

t2_04edge
Input{"mat":[[0,0,0,0],[0,1,1,1],[0,1,1,1],[0,1,1,1]]}
Expected[[0,0,0,0],[0,1,2,3],[0,1,2,3],[0,1,2,3]]

Zeros clustered in one corner, distances grow as you move away.

t3_01corner
Input{"mat":[[1,1,1],[1,1,1],[1,1,0]]}
Expected[[4,3,2],[3,2,1],[2,1,0]]

Distances increase correctly from single zero in corner.

t3_02corner
Input{"mat":[[1,0,1],[1,1,1],[1,1,1]]}
Expected[[1,0,1],[2,1,2],[3,2,3]]

Distances propagate correctly from zero in middle top row.

t3_03corner
Input{"mat":[[0,1,1,0,1],[1,1,1,1,1],[1,1,0,1,1]]}
Expected[[0,1,1,0,1],[1,2,1,1,2],[1,1,0,1,2]]

Multiple zeros scattered, distances computed correctly.

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

Large matrix with 100 rows and 1000 columns (total 100,000 cells). Multi-source BFS O(m*n) must complete within 2 seconds.

Practice

(1/5)
1. Consider the following Python code to find the town judge:
def findJudge(n, trust):
    trust_score = [0] * (n + 1)
    for a, b in trust:
        trust_score[a] -= 1
        trust_score[b] += 1
    for i in range(1, n + 1):
        if trust_score[i] == n - 1:
            return i
    return -1

print(findJudge(3, [[1,3],[2,3]]))
What is the output of this code?
easy
A. 1
B. -1
C. 3
D. 2

Solution

  1. Step 1: Trace trust_score updates

    For trust pairs [1,3] and [2,3]: trust_score[1] -= 1, trust_score[3] += 1; trust_score[2] -= 1, trust_score[3] += 1. Final trust_score = [0, -1, -1, 2].
  2. Step 2: Identify judge by trust_score == n-1

    n=3, so n-1=2. Only person 3 has trust_score 2, so return 3.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Person 3 trusted by 2 others, trusts nobody [OK]
Hint: Trust score array sums trust and distrust correctly [OK]
Common Mistakes:
  • Returning the person who trusts others
  • Off-by-one indexing in trust_score
  • Confusing trust_score values with counts
2. Consider the following Python code implementing flood fill using DFS. Given the input image = [[1,1,1],[1,1,0],[1,0,1]], starting pixel (sr=1, sc=1), and newColor=2, what is the final image returned?
easy
A. [[1,1,1],[1,2,0],[1,0,1]]
B. [[2,2,2],[2,2,0],[2,0,2]]
C. [[2,2,2],[2,2,0],[2,0,1]]
D. [[2,2,2],[2,2,2],[2,2,2]]

Solution

  1. Step 1: Trace dfs starting at (1,1) with original color=1

    The pixel at (1,1) is recolored to 2. Its neighbors with color 1 are (0,1), (2,1) is 0 so skipped, (1,0), and (1,2) is 0 skipped.
  2. Step 2: Recursively recolor connected pixels with color 1

    All connected pixels with color 1 reachable from (1,1) are recolored to 2, resulting in [[2,2,2],[2,2,0],[2,0,1]]. The pixel at (2,2) remains 1 as it is not connected 4-directionally.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Only connected pixels with original color changed [OK]
Hint: Trace DFS calls carefully to find connected pixels [OK]
Common Mistakes:
  • Changing pixels diagonally connected
  • Forgetting to check boundaries
3. Consider the following code snippet that finds the smallest set of vertices to reach all nodes in a DAG. Given n = 4 and edges = [[0,1],[1,2],[2,3]], what is the final returned list?
easy
A. [0]
B. [3]
C. [0, 1]
D. [1]

Solution

  1. Step 1: Initialize in-degree and queue

    Nodes: 0,1,2,3; in-degree: [0,1,1,1]. Only node 0 has zero in-degree, so queue = [0], result = [0].
  2. Step 2: Process queue

    Pop 0, decrement in-degree of 1 to 0, enqueue 1. Pop 1, decrement in-degree of 2 to 0, enqueue 2. Pop 2, decrement in-degree of 3 to 0, enqueue 3. Pop 3, no neighbors.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Only node 0 has zero in-degree initially, so result is [0] [OK]
Hint: Only nodes with zero in-degree initially are in the result [OK]
Common Mistakes:
  • Returning nodes that become zero in-degree later
  • Returning all nodes visited in BFS
  • Confusing final queue state with result
4. Given the following Python code snippet implementing the BFS approach for Pacific Atlantic Water Flow, and the input heights = [[1,2,2],[3,2,3],[2,4,5]], what is the value of pacific_reachable after initializing the queues and marking the border cells?
easy
A. [[True, True, True], [True, False, False], [True, False, False]]
B. [[True, True, True], [True, False, False], [True, False, True]]
C. [[True, True, True], [False, False, False], [True, False, False]]
D. [[True, False, True], [True, False, False], [True, False, False]]

Solution

  1. Step 1: Mark Pacific border cells

    Pacific borders are first row and first column. So pacific_reachable[0][j] and pacific_reachable[i][0] are True.
  2. Step 2: Fill pacific_reachable matrix

    For m=3, n=3, first row and first column cells are True, others False initially.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    First row and first column are True, rest False [OK]
Hint: Pacific reachable True on top row and left column [OK]
Common Mistakes:
  • Forgetting to mark all border cells
  • Marking wrong cells True
5. What is the time complexity of the optimal approach using a single trust score array to find the town judge, given n people and m trust pairs?
medium
A. O(n * m) because we scan trust pairs for each person
B. O(n^2) because we check trust relationships pairwise
C. O(m^2) because trust pairs are nested in loops
D. O(n + m) because we process each trust pair once and then scan all people once

Solution

  1. Step 1: Identify loops in the algorithm

    The algorithm iterates once over all trust pairs (m) and then once over all people (n).
  2. Step 2: Combine complexities

    Processing trust pairs is O(m), scanning people is O(n), total O(n + m).
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Single pass over trust and people arrays [OK]
Hint: Single pass over trust pairs and people yields O(n + m) [OK]
Common Mistakes:
  • Assuming nested loops cause O(n*m)
  • Confusing trust pairs count with people count
  • Ignoring linear scans after trust processing
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard