Question:
Input is a NxN matrix which contains only 0′s and 1′s. The condition is no 1 will occur in a row after 0. Find the index of the row which contains maximum number of zeros.
Example: lets say 5×5 matrix
1 0 0 0 0
1 1 0 0 0
1 1 1 1 1
0 0 0 0 0
1 1 1 0 0
For this input answer is 4th row.
solution should have time complexity less than N^2
http://www.geeksforgeeks.org/forums/topic/amazon-interview-question-for-software-engineerdeveloper-about-algorithms-24/
Solutions:
1. O(n2)Solution:
Start from a11 to a1n (go through the column) once 0 is met, return current index of row. If no 0 is met, go through the second column (a21 to a2n).
在最坏情况下需要遍历矩阵中的每个元素。
2. O(nlogn)Solution:
Search each row from top to down, in each row, use binary search to get the index of first 0. Use a variable to save the max index of 0. In worst case, O(nlogn) in time complexity.
3. O(n)Solution:
Start from the top right element a1n, if 0 is met, move left, if 1 is met or left corner is reached, record current index of row to variable T, then move down until 0 is met. Repeat these steps until move down to the bottom of matrix (anx) or left corner of matrix (ax1). The value of T is the answer. In worst case, time complexity O(2n) = O(n).
Code of Solution 3:
#include<stdio.h> #include <ctime> #include <cstdlib> using namespace std; int MaximumZeroRow(int** matrix, int size){ if(matrix == NULL) return 0; int i = 0, j = size - 1, T = 0; while(1){ if(!matrix[i][j]){ j--; } if(matrix[i][j] || j < 0){ T = i; i++; } if( i > (size - 1) || j < 0) break; } return T; } int main(){ srand(time(0)); int **array; array = new int *[5]; for(int i = 0; i < 5; i++){ array[i] = new int[5]; for(int j = 0; j < 5; j++){ array[i][j] = (j == 0 ? (rand() & 1) : (rand() & 1) & array[i][j-1]); printf("%d ", array[i][j]); } printf(" "); } printf(" "); printf("Max 0 row index: %d ", MaximumZeroRow(array, 5)); return 0; }