Round 1
Questions:
You are given a 2D grid representing a farmland where each cell can either be a defender or a farmer. The grid is represented as a 2D array of integers, where 1
denotes a defender and 0
denotes a farmer. Your task is to determine the position of the most vulnerable farmer in the grid. A farmer's vulnerability is defined by the number of defenders present before them in their row.
Objective: Find the position of the most vulnerable farmer, defined as the farmer with the fewest defenders (1s) in front of them in their respective row. If multiple farmers have the same vulnerability, return the position of the first farmer encountered in a row-wise order (top to bottom).
Input:
- A 2D integer array
grid
of sizen x m
, wheren
is the number of rows andm
is the number of columns. - Each element in the grid is either
0
(farmer) or1
(defender).
Output:
- An integer array of size
2
, where:- The first element is the 1-based index of the row where the most vulnerable farmer is located.
- The second element is the 1-based index of the column where the most vulnerable farmer is located.
Constraints:
- The grid will have at least one farmer and at least one defender.
- The number of rows (
n
) and columns (m
) will be within reasonable limits for efficient computation.
Candidate's Approach
- Initialize variables to track the minimum number of defenders and the position of the most vulnerable farmer.
- Iterate through each row of the grid:
- For each farmer (0), count the number of defenders (1s) before them in that row.
- If the count is less than the current minimum, update the minimum and store the farmer's position.
- Return the position of the most vulnerable farmer in 1-based indexing.
Interviewer's Feedback
No feedback provided.