I was asked a question in the interview:
Given matrix
A
and matrixB
, I have to write a program to find out whether matrixB
exist in matrixA
.
The problem is I have to do it in O(n)
time. This the only approach I have come up:
public class Matrix {
public static void main(String[] args) {
boolean flag = false;
int a[][] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};
int b[][] = {
{11, 12},
{15, 16}};
for (int i = 0; i < a.length - b.length + 1; i++) {
for (int j = 0; j < a[0].length - b[0].length + 1; j++) {
if (a[i][j] == b[0][0]) {
flag = true;
for (int k = 0; k < b.length; k++) {
for (int l = 0; l < b[0].length; l++) {
if (a[i + k][j + l] != b[k][l]) {
flag = false;
break;
}
}
}
if (flag) {
System.out.println("i= " + i + " j= " + j);
return;
}
}
}
}
}
}
I don't know how to convert it to O(n)
.
Is there any technique to search if small matrix B
exist in big matrix A
in O(n)
?