In a nutshell: You have two snakes. Consider them as two strings; each cell being a letter of the corresponding strings. Now, to find the match, you have to find the largest common substring from these two strings.

Brute force approach: Take the first letter of the first string and try to find in second string. if both strings contain that letter, see if the next letters of both string matches too. Continue until a pair don't match. Now you've found a common substring.

As the letters of a string are unique, you will find at most one match for each letter on both strings. So if a letter is part of some substring you've already matched, you don't have to consider that letter for any other substrings. Thus, the complexity of brute force approach is O(n2)O(n^2).

Solution: Now if you put the letters of the second string in some map to find their index in O(log(n))O(log (n)), you can solve this problem in O(n×log(n))O(n \times log(n)), which is the intended time complexity of this problem.

Statistics

77% Solution Ratio
cloud007Earliest, Oct '19
MR.Jukerburg11Fastest, 0.0s
IMGR00TLightest, 2.9 MB
sk_royShortest, 567B
Toph uses cookies. By continuing you agree to our Cookie Policy.