• Tutorials
  • DSA
  • Data Science
  • Web Tech
  • Courses
July 04, 2022 |7.8K Views

Check if two strings have a common substring

  Share   Like
Description
Discussion

A basic approach runs in O(n^2), where we compare every character of string 1 with every character of string 2 and replace every matched character with a “_” and set flag variable as true.


An efficient approach works in O(n). We basically need to check if there is a common character or not. We create a vector of size 26 for alphabets and initialize them as 0. For every character in string 1 we increment vector index of that character eg: v[s1[i]-‘a’]++, for every character of string 2 we check vector for the common characters if v[s2[i]-‘a’] > 0 then set flag = true and v[s2[i]-‘a’]– such that one character of string 2 is compared with only one character of string 1.


Check if two strings have a common substring : https://www.geeksforgeeks.org/check-two-strings-common-substring/