Tuesday, August 24, 2010

Given two strings of a and b. Find the max window in a and b where the substrings in the window are anagrams.

Problem description:

1. Given two strings a and b, find the max value of "length" where for some i and j, a.substring(i, i+length) and b.substring(j, j+length) are anagrams.

2. Given two strings a and b, find the max window of matching patterns between a and b where the pattern matching doesn't have to be an exact match but also can be a permutation of each other. (which is essentially anagrams...)

Algorithm:

let m = a.length;
let n = b.length;
let matrix = int[m][n]

if a[i] == b[j] then matrix[i][j] = 1
else matrix[i][j] = 0

With the matrix populated by the routines above, find the largest square that meets the following two conditions:
  • no column contains all 0s. For each column, at least one cell is 1
  • no rows contains all 0s
The time complexity is O(n^2). I don't believe it can be done in O(nlogn). But I could be wrong.

Someone was asked the following question during interview: if m = n, would that help speeding up the complexity?

Well, I have no idea...

1 comment:

Pawel said...

Hi
I am trying to solve this problem as well now.
I like the idea of representing the strings in a matrix. However I think for the square it is not enough to find non-zero columns and rows. In a square, for each row, in the intersecting (through 1's) columns, the number of 1's must be the same of the row and the column.
Anyway, have you managed to get this algorythm optimized? Would you mind sharing your findings?
Thanks
Pawel