Interview Question
Country: India
Interview Type: Written Test
I had to correct this sentence:
"it means, for two cells in path, the one which lies on the lower layer should be on the left-bottom of the second one."
it should be "left-above".
Sorry, I can't update it since I accidentally posted it anonymously.
public void mostBeautifuPath (int [][] matrix){
int r = matrix.length ;
int c = matrix[0].length ;
int [] dp = new int [r * c] ;
for (int i = 1 ; i < c ;++i ) {
dp[id (0 , i, c)] = id (0 , i - 1, c) ;
}
for (int i = 1 ; i < r ; ++i) {
dp[id (i , 0, c)] = id (i - 1 , 0, c) ;
}
for (int i = 1 ; i < r ; ++i) {
for (int j = 1 ; j < c ; ++j ) {
if (matrix[i - 1][j] <= matrix[i][j - 1]) {
dp[id(i , j , c)] = id (i - 1, j, c);
} else {
dp[id(i , j , c)] = id (i, j - 1, c);
}
}
}
int i = dp.length - 1 ;
List<Integer> rst = new ArrayList<> ();
int [] start = coordinator (dp.length - 1, c) ;
rst.add(matrix[start[0]][start[1]]) ;
while (i > 0 ) {
i = dp[i] ;
int [] pre = coordinator (i, c) ;
rst.add(matrix[pre[0]][pre[1]]) ;
}
Collections.sort(rst);
for (int v : rst) {
System.out.print(v + " ");
}
System.out.println();
}
public int id (int x, int y, int c){
return x * c + y ;
}
public int [] coordinator (int id, int c){
return new int [] {id / c , id % c } ;
}
I think it's wrong.
What is the result of your program for this input?
3 4
200 10 7 3
20 4 5 6
2 100 1 300
Answer should be : 200 --> 20 --> 2 --> 100 --> 1 --> 300
I don't think it works. Here is the example:
1,23,7
2,90,15
9,56,77
The path 1->2->90->15->7 gives us 1271590 order,
while you provide us with 1->23->7->15->77 which is 17152377 and higher lexicographically.
@ Mehrdad you are right ,
I had another solution which is using brutal force , but I do not think brutal force is able to pass the big data test
Very interesting problem.
Here's my solution with O(N*M*log(N+M)).
I want to sort all the numbers, and make the path from smallest to largest.Each time we just need to make sure that the current number can be added to the path without violating the rule(using right and down moves).
When it comes to traversing a gride using right and down moves, it's usually useful to think about the problem as traversing the gride layer by layer that layers are secondary diagnols.
When we traverse the layers (secondary diagnols), following condition always should be true.
For two cells (x1,y1) , (x2,y2) in the path: if (x1+y1)<(x2+y2) then x1<=x2 && y1<=y2.
it means, for two cells in path, the one which lies on the lower layer should be on the left-bottom of the second one. (which is obvious).
Now, we can use a set(or sorted array) for having visited layers.Each time we just have to make sure that the current number can hold the above condition true,i.e, for its two immediate layers (above and down) the condition is true.
Time Complexity:
Iterate over all number(N*M) and each time a binary search(lower_bound) on the set.
Totaly: O(N*M*log(N+M))
- Anonymous July 27, 2015