TASTR - Editorial

PROBLEM LINKS

Practice
Contest

DIFFICULTY

MEDIUM

PREREQUISITES

Suffix Array, Longest Common Prefix Array

PROBLEM

Given two strings a and b, let A be the set of all substrings of a, and B be the set of all substrings of b.

Find the number of unique strings in A plus the number of unique strings in B, that are not common to both A and B.

QUICK EXPLANATION

Efficient solutions to a large set of problems on strings are approachable by use of Suffix Arrays (or Trees). If you have not yet added Suffix Sorting (for construction of Suffix Arrays) to your skill-set, then this is the perfect problem to do so.

Suffix Sorting can be done using

  • Manber Myers algorithm in O(L log L) time
  • Karkkainan Sanderā€™s algorithm in O(L) time

Longest Common Prefixes of adjacent items in the list of sorted suffixes is a classical problem in strings. Most texts discuss construction of Suffix Arrays immediately followed by calculation of LCP arrays.

The LCP Array can be found by augmenting the Suffix Sorting algorithms above. The time complexity for LCP Array calculation will be exactly equal to the time complexity of the Suffix Sorting. You can find it as an entirely different step as well, following the Suffix Sorting.

Both O(L) and O(L log L) approaches will fit within the time limit for this problem. Hence, choose as you please :slight_smile:

Let us assume that we can find the number of unique sub-strings of a string by use of the LCP array for the suffixes of that string. (We will see the algorithm to do so in the EXPLANATION section)

U(A) = number of unique strings in A

We are given two strings a and b and their set of substrings A and B respectively. We wish to find

U(A) + U(B) - U(A intersection B)

Which is equal to

U(A) + U(B) - (U(A union B) - U(A) - U(B))

Or

2*U(A) + 2*U(B) - U(A union B)

EXPLANATION

Let us see how to find the number of unique substrings of a string by using the LCP array.

  • If we consider all the prefixes of all the suffixes, we would be considering the entire set of sub-strings.
  • The LCA array helps us determine how many prefixes to ignore for each suffix
  • We of course do not ignore any prefix of the first suffix. These are all valid and unique substrings.
Let s be given string
    indexes in s are 1-based
Let S be the suffix array
    S stores the list of 1-based indexes
    that represent the start position of the suffix of s
Let L be the LCP array
    L(i) is the longest common prefix between
    the suffixes starting from S(i) and S(i-1)
    Thus, L is only defined from 2 to |s|

uniq_sub_strings = |s| - S[1] + 1
// thus we count all prefixes of the first suffix

for i = 2 to N
    uniq_sub_strings += |s| - S[i] + 1 - L[i]

Let us try this with an example to see why this is correct.

s = abaabba
S = [
    7,    // a
    3,    // aabba
    1,    // abaabba
    4,    // abba
    6,    // ba
    2,    // baabba
    5     // bba
]
L = [
    0,    // not defined for L[1]
    1,    // a is the common prefix
    1,    // a
    2,    // ab
    0,    // nothing
    2,    // ba
    1     // b
]

uniq_sub_strings =
    1 + 4 + 6 + 2 + 2 + 4 + 2 = 21

Thus, there are 21 substrings (out of 28) that are unique. You can work this out by deducing that the sub-strings that are not unique (and hence werenā€™t counted are)

{
    a,  // prefix of aabba
        // since a was counted as prefix of "a"
    a,  // prefix of abaabba
    a,  // prefix of abba
    ab, // prefix of abba
        // since ab was counted as prefix of "abaabba"
    b,  // prefix of baabba
        // since b was counted as prefix of "ba"
    ba, // prefix of baabba
        // since ba was counted as prefix of "ba"
    b   // prefix of bba
}

Now, you can find U(A) and U(B) by using the above algorithm. The only part that remains is to calculate U(A union B).

This can be done by considering a string

c = a + "$" + b

We can find all the unique substrings of c and reduce from the result, all the strings that contain the character ā€˜'</b>. We know that all the different strings that contain <b>'ā€™ are unique anyway, since ā€˜$ā€™ is not part of the alphabet.

There are (|a|+1) * (|b|+1) substrings of c that contain ā€˜$ā€™.

Thus, we can find U(A union B), the number of unique substrings that exists in either A, or B.

We can find the number of unique sub-strings of either a, or b, but not both, in time O(F(|a|) + F(|b|) + F(|a+b|), where F(n) is the complexity of calculating the Suffix Array or the LCA Array (which ever is more). In the best implementation, F(n) = O(n). But the problem may be solved even with F(n) = O(n log n).

SETTERā€™S SOLUTION

Can be found here.

TESTERā€™S SOLUTION

Can be found here.

22 Likes

My first solution constructed the suffix array (in O(Nlog(N)) time) for each string independently (A, B and the union of A and B) and I got Time limit exceeded. I had to change my algorithm so that it computed everything only from the suffix array (and the LCPs) of the union of A and B. I thought that was intended, but now I see that I probably have some inefficiencies in my suffix array routines, which I will have to identify.

2 Likes

does the solution that uses hashes exist ?

Where can i read more about suffix array and LCP array? (algorithm and application)

3 Likes

Amazing tutorialā€¦gr8t work!!!

1 Like

http://www.codechef.com/viewsolution/1966634

My solution works on all test cases i found

but still gives runtime error

please help

@anton_lunyov sir may u plzz provide me the test cases where this solution is failed CodeChef: Practical coding for everyone
thanx in advanceā€¦:slight_smile:

I canā€™t seem to visualise this part

U(A) + U(B) - U(A intersection B)
Which is equal to
U(A) + U(B) - (U(A union B) - U(A) - U(B))

Isnā€™t U(A intersection B) supposed to be = to U(A) + U(B) - U(A union B)

9 Likes

Can someone help me with the stdin and stdout for node.js. My code is as follows

process.stdin.resume();

process.stdin.setEncoding(ā€˜utf8ā€™);

process.stdin.on(ā€˜dataā€™, function (chunk) {
var lines = chunk.toString().split(ā€™\nā€™);

var stringDiff = function(a,b){
	var aSet = getAllSubstring(a);
	var bSet = getAllSubstring(b);
	var nSet = difference(aSet, bSet);
	nSet = nSet.concat(difference(bSet, aSet));
	
	return nSet.length;
}

var difference = function(a,b){
	var nSet = [];
	for(var i in a){
		var found = false;
		for(x in b){
			if(a[i] === b[x]){
				found = true;
				break;
			}
		}
		
		if(!found){ nSet.push(a[i])};
	}
	return nSet;
}

var getAllSubstring = function(s){
	var aSet = [];
	var i = 1;
	var j = 0;
	while(i<=s.length&&j<s.length){
		var next = s.substring(j,i);
		if(aSet.indexOf(next)<0){
			aSet.push(next);
		}
		
		
		if(i===s.length){
			j++;
			i = j+1;
		}else{
			i++;
		}
	}
	return aSet;
}

var diff = stringDiff(lines[0], lines[1]);
process.stdout.write(diff+'\n');
process.exit();

});

@anton sir would you please tell me where is my code failing hereā€™s my code :frowning:

@anton_lunyov : sir please help me every time i get a run time error(SIGSEGV)ā€¦

http://www.codechef.com/viewsolution/1966634

hello,
could you just tell me weather my codeā€™s output is correct or not, irrespective of time exceed errorā€¦

why doesnt work?

module Main where
 
import Data.List
import System.Exit
 
 
al1 xs = nub . concat . map (drop 1 . inits) . tails $ xs
 
cmp xs xz = [ x | x <- ((al1 xs)++(al1 xz)), notElem x (intersect (al1 xs) (al1 xz) )] 
   
 
main = do
    line <- getLine
    line2 <- getLine
    putStr $ show $ length $ cmp line line2
    exitWith ExitSuccess

This is my code in python. it works fine on my system but dont know why it is not working in codechef

http://ww2.codechef.com/viewsolution/2075046

getting run time error NZEC. first submission in codechef. so dont know much abt online compilers. plz help me out sir CodeChef: Practical coding for everyone

Wowā€¦ that was a quite a sleek approachā€¦ Nice one

This problem really showed our ā€œlevelā€ :slight_smile:

1 Like

I did the same thing as the tester . My solutions (during the contest[CodeChef: Practical coding for everyone]) and after the contest with some optimizations (CodeChef: Practical coding for everyone) both TLE ā€¦ Is this too strict for Java ?
EDIT: I think he has a better Suffix array function.

My O(n*(logn)*(logn)) passes !

Yes @acmonster construct LCP array using hashes in O(N log^2 N) time. We can compare two suffixes in O(log N) time using hashes. So we can sort them in O(N log^2 N) time. And then calculate LCP array in O(N log N) time.