PPractick

DSA interview question

Row with the Maximum Number of 1s

Easy · Algorithms · Topics: binary search, matrix

The problem

A factory's quality dashboard stores each production line's test results as a row of 0s and 1s, sorted so that the failures (0) come first and the passes (1) come after. The manager wants the line with the most passes, and if several tie, the one with the smallest index. Counting every cell is O(n × m). Because each row is sorted, the number of 1s in a row is m − (index of the first 1), which binary search finds in O(log m). An even slicker O(n + m) walk starts at the top-right corner and moves left or down.

Example: [[0, 1, 1, 1], [0, 0, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0]] → 2.

Function signature

int rowWithMax1s(const vector<vector<int>>& grid);  // row index, first on ties, -1 if there are no 1s

Test cases

Input gridOutputExplanation
[[0,1,1,1],[0,0,1,1],[1,1,1,1],[0,0,0,0]]2Row 2 has four 1s
[[0,0],[1,1]]1
[[0,0],[0,0]]-1No 1s anywhere
[[0,1],[0,1],[1,1]]2
[[1]]0
[[0,1,1],[0,1,1]]0Tie: the first row wins

(Confirm: every row is sorted with 0s before 1s; return the first row on ties; -1 if there are no 1s.)

How interviewers phrase it

Clarifying questions to ask

  1. Is each row sorted (all 0s then all 1s)?
  2. What to return on ties, and when there are no 1s at all?
  3. What are the dimensions? (Decides between O(n log m) and O(n + m).)

Follow-ups to expect

  1. "How do you count 1s in a sorted row quickly?"
  2. "Can you do better than O(n log m)?"
  3. "Why does the staircase keep the first row on ties?"
  4. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in