First Completely Painted Row or Column - Problem

You are given a 0-indexed integer array arr, and an m x n integer matrix mat. Both arr and mat contain all the integers in the range [1, m * n].

Go through each index i in arr starting from index 0 and paint the cell in mat containing the integer arr[i].

Return the smallest index i at which either a row or a column will be completely painted in mat.

Input & Output

Example 1 — Basic Case
$ Input: arr = [1,3,4,2], mat = [[1,4],[2,3]]
Output: 2
💡 Note: Paint cells in order: (0,0)→1, (1,1)→3, (0,1)→4. After painting 4, row 0 is complete: [1,4]. Return index 2.
Example 2 — Column Completion
$ Input: arr = [2,8,7,4,1,3,5,6,9], mat = [[3,2,5],[1,4,6],[8,7,9]]
Output: 3
💡 Note: Paint: (0,1)→2, (2,0)→8, (2,1)→7, (1,1)→4. After painting 4, column 1 is complete: [2,4,7]. Return index 3.
Example 3 — Single Row
$ Input: arr = [5,1,3], mat = [[1,3,5]]
Output: 2
💡 Note: Paint: (0,2)→5, (0,0)→1, (0,1)→3. After painting 3, the entire row is complete. Return index 2.

Constraints

  • m == mat.length
  • n == mat[i].length
  • arr.length == m * n
  • 1 ≤ m, n ≤ 105
  • 1 ≤ m * n ≤ 105
  • 1 ≤ arr[i], mat[r][c] ≤ m * n
  • All the integers of arr are unique
  • All the integers of mat are unique

Visualization

Tap to expand
First Completely Painted Row or Column INPUT arr = [1, 3, 4, 2] 1 i=0 3 i=1 4 i=2 2 i=3 mat (2x2 matrix) 1 4 2 3 R0 R1 C0 C1 m = 2, n = 2 Range: [1, 4] Paint cells in order of arr ALGORITHM STEPS 1 Build Position Map Map each value to (row, col) 1 --> (0,0) 3 --> (1,1) 4 --> (0,1) 2 --> (1,0) 2 Init Counters row_cnt=[0,0], col_cnt=[0,0] 3 Process arr[i] Increment row/col counters i=0: Paint 1(0,0) R[1,0] C[1,0] i=1: Paint 3(1,1) R[1,1] C[1,1] i=2: Paint 4(0,1) R[2,1] C[1,2] R[0]=2=n --> Row 0 FULL! C[1]=2=m --> Col 1 FULL! 4 Check Completion If cnt == m or n, return i FINAL RESULT Matrix at i=2 1 4 2 3 Row 0 COMPLETE! Col 1 COMPLETE! Painted cell Unpainted cell OUTPUT 2 Smallest index i = 2 Key Insight: Use a hash map to store (value --> position) for O(1) lookup. Maintain row and column counters. For each arr[i], increment the counter for its row and column. When any counter reaches the row/column size (n or m), that row/column is complete. Time: O(m*n), Space: O(m*n) TutorialsPoint - First Completely Painted Row or Column | Optimized with Counters
Asked in
Google 12 Amazon 8 Microsoft 6
23.0K Views
Medium Frequency
~15 min Avg. Time
945 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen