Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Longest common anagram subsequence from N strings
Next article icon

Longest Common Substring in an Array of Strings

Last Updated : 28 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a list of words sharing a common stem i.e the words originate from same word for ex: the words sadness, sadly and sad all originate from the stem ‘sad’. 
Our task is to find and return the Longest Common Substring also known as stem of those words. In case there are ties, we choose the smallest one in alphabetical order. 

Examples: 

Input : grace graceful disgraceful gracefully
Output : grace
Input : sadness sad sadly
Output : sad

The idea is to take any word from the list as reference and form all its substrings and iterate over the entire list checking if the generated substring occurs in all of them.

Below is the implementation of the above idea:

C++
// C++ program to find the stem of given list of // words #include <bits/stdc++.h> using namespace std;  // function to find the stem (longest common // substring) from the string array string findstem(vector<string> arr) {     // Determine size of the array     int n = arr.size();      // Take first word from array as reference     string s = arr[0];     int len = s.length();      string res = "";      for (int i = 0; i < len; i++) {         for (int j = i + 1; j <= len; j++) {             // generating all possible substrings             // of our reference string arr[0] i.e s             string stem = s.substr(i, j);             int k = 1;             for (k = 1; k < n; k++) {                 // Check if the generated stem is                 // common to all words                 if (arr[k].find(stem) == std::string::npos)                     break;             }              // If current substring is present in             // all strings and its length is greater             // than current result             if (k == n && res.length() < stem.length())                 res = stem;         }     }      return res; }  // Driver code int main() {     vector<string> arr{ "grace", "graceful", "disgraceful",                         "gracefully" };      // Function call     string stems = findstem(arr);     cout << stems << endl; }  // This code is contributed by // sanjeev2552 
Java
// Java program to find the stem of given list of // words import java.io.*; import java.util.*;  class stem {      // function to find the stem (longest common     // substring) from the string  array     public static String findstem(String arr[])     {         // Determine size of the array         int n = arr.length;          // Take first word from array as reference         String s = arr[0];         int len = s.length();          String res = "";          for (int i = 0; i < len; i++) {             for (int j = i + 1; j <= len; j++) {                  // generating all possible substrings                 // of our reference string arr[0] i.e s                 String stem = s.substring(i, j);                 int k = 1;                 for (k = 1; k < n; k++)                      // Check if the generated stem is                     // common to all words                     if (!arr[k].contains(stem))                         break;                  // If current substring is present in                 // all strings and its length is greater                 // than current result                 if (k == n && res.length() < stem.length())                     res = stem;             }         }          return res;     }      // Driver Code     public static void main(String args[])     {         String arr[] = { "grace", "graceful",                          "disgraceful","gracefully" };                // Function call         String stems = findstem(arr);         System.out.println(stems);     } } 
Python
# Python 3 program to find the stem # of given list of words  # function to find the stem (longest # common substring) from the string array   def findstem(arr):      # Determine size of the array     n = len(arr)      # Take first word from array     # as reference     s = arr[0]     l = len(s)      res = ""      for i in range(l):         for j in range(i + 1, l + 1):              # generating all possible substrings             # of our reference string arr[0] i.e s             stem = s[i:j]             k = 1             for k in range(1, n):                  # Check if the generated stem is                 # common to all words                 if stem not in arr[k]:                     break              # If current substring is present in             # all strings and its length is greater             # than current result             if (k + 1 == n and len(res) < len(stem)):                 res = stem      return res   # Driver Code if __name__ == "__main__":      arr = ["grace", "graceful",            "disgraceful", "gracefully"]          # Function call     stems = findstem(arr)     print(stems)  # This code is contributed by ita_c 
C#
// C# program to find the stem of given list of  // words  using System; using System.Collections.Generic;  class stem {      // function to find the stem (longest common      // substring) from the string array      public static String findstem(String []arr)      {          // Determine size of the array          int n = arr.Length;           // Take first word from array as reference          String s = arr[0];          int len = s.Length;           String res = "";           for (int i = 0; i < len; i++)          {              for (int j = i + 1; j <= len; j++)             {                   // generating all possible substrings                  // of our reference string arr[0] i.e s                  String stem = s.Substring(i, j-i);                  int k = 1;                  for (k = 1; k < n; k++)                       // Check if the generated stem is                      // common to all words                      if (!arr[k].Contains(stem))                          break;                                   // If current substring is present in                  // all strings and its length is greater                  // than current result                  if (k == n && res.Length < stem.Length)                      res = stem;              }          }           return res;      }       // Driver Code      public static void Main(String []args)      {          String []arr = { "grace", "graceful", "disgraceful",                                              "gracefully" };          // Function call         String stems = findstem(arr);          Console.WriteLine(stems);      }  }   // This code contributed by Rajput-Ji 
JavaScript
// JavaScript program to find the stem of given list of // words function findstem(arr) {  // Determine size of the array let n = arr.length;  // Take first word from array as reference let s = arr[0]; let len = s.length;  let res = "";  for (let i = 0; i < len; i++) {     for (let j = i + 1; j <= len; j++) {          // generating all possible substrings         // of our reference string arr[0] i.e s         let stem = s.substring(i, j);         let k = 1;         for (k = 1; k < n; k++) {              // Check if the generated stem is             // common to all words             if (!arr[k].includes(stem))                 break;         }          // If current substring is present in         // all strings and its length is greater         // than current result         if (k === n && res.length < stem.length)             res = stem;     } }  return res; }  // Driver Code let arr = ["grace", "graceful", "disgraceful", "gracefully"];  // Function call let stems = findstem(arr); console.log(stems); 
PHP
<?php // PHP program to find the stem of given list of  // words      // function to find the stem (longest common      // substring) from the string array     function findstem($arr)     {         // Determine size of the array         $n = count($arr);          // Take first word from array as reference         $s = $arr[0];         $len = strlen($s);                  $res = "";          for ($i = 0; $i < $len; $i++)         {             for ($j = $i+1; $j <=$len; $j++)              {                  // generating all possible substrings                 // of our reference string arr[0] i.e s                 $stem = substr($s,$i, $j-$i);                                  $k = 1;                 for ($k = 1; $k < $n; $k++)                       // Check if the generated stem is                     // common to all words                     if (!strpos($arr[$k],$stem))                         break;                                  // If current substring is present in                 // all strings and its length is greater                  // than current result                 if ($k <= $n && strlen($res) < strlen($stem))                     $res = $stem;                              }         }          return $res;     }      // Driver Code     $arr = array( "grace", "graceful",                   "disgraceful", "gracefully" );      // Function call     $stems = findstem($arr);     print($stems);      // This code is contributed by mits ?> 

Output
grace 

Time Complexity: O(L2 * n * m)
Auxiliary Space: O(L).



Next Article
Longest common anagram subsequence from N strings
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • DSA
  • Strings
  • Java-Strings
Practice Tags :
  • Java-Strings
  • Strings

Similar Reads

  • Longest common anagram subsequence from N strings
    Given N strings. Find the longest possible subsequence from each of these N strings such that they are anagram to each other. The task is to print the lexicographically largest subsequence among all the subsequences. Examples: Input: s[] = { geeks, esrka, efrsk } Output: ske First string has "eks",
    11 min read
  • Count of Superstrings in a given array of strings
    Given 2 array of strings X and Y, the task is to find the number of superstrings in X. A string s is said to be a Superstring, if each string present in array Y is a subsequence of string s . Examples: Input: X = {"ceo", "alco", "caaeio", "ceai"}, Y = {"ec", "oc", "ceo"}Output: 2Explanation: Strings
    8 min read
  • Find the longest Substring of a given String S
    Given a string S of length, N. Find the maximum length of any substring of S such that, the bitwise OR of all the characters of the substring is equal to the bitwise OR of the remaining characters of the string. If no such substring exists, print -1. Examples: Input: S = "2347"Output: 3?Explanation:
    10 min read
  • Longest substring of 0s in a string formed by k concatenations
    Given a binary string of length n and an integer k. Consider another string T which is formed by concatenating the given binary string k times. The task is to print the maximum size of a substring of T containing only zeroes. Examples: Input: str = 110010, k = 3 Output: 2 str = 110010 T = 1100101100
    8 min read
  • Longest String Chain - Chain of words in an Array
    Given an array of words where each word consists of lowercase English letters, we need to find the longest word chain possible. A word wordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal
    15+ min read
  • Longest common substring in binary representation of two numbers
    Given two integers n and m. Find the longest contiguous subset in binary representation of both the numbers and their decimal value. Example 1: Input : n = 10, m = 11 Output : 5 Explanation : Binary representation of 10 -> 1010 11 -> 1011 longest common substring in both is 101 and decimal val
    7 min read
  • LCS (Longest Common Subsequence) of three strings
    Given 3 strings say s1, s2 and s3. The task is to find the longest common sub-sequence in all three given sequences. Examples: Input: s1 = "geeks" , s2 = "geeksfor", s3 = "geeksforgeeks"Output : 5Explanation: Longest common subsequence is "geeks" i.e., length = 5Input: s1= "abcd1e2" , s2= "bc12ea" ,
    15+ min read
  • Print the longest common substring
    Given two strings ‘X’ and ‘Y’, print the length of the longest common substring. If two or more substrings have the same value for the longest common substring, then print any one of them. Examples: Input : X = "GeeksforGeeks", Y = "GeeksQuiz" Output : Geeks Input : X = "zxabcdezy", Y = "yzabcdezx"
    15+ min read
  • Longest Common Substring
    Given two strings 's1' and 's2', find the length of the longest common substring. Example: Input: s1 = "GeeksforGeeks", s2 = "GeeksQuiz" Output : 5 Explanation:The longest common substring is "Geeks" and is of length 5. Input: s1 = "abcdxyz", s2 = "xyzabcd" Output : 4Explanation:The longest common s
    15+ min read
  • Longest Common Prefix using Binary Search
    Given an array of strings arr[], the task is to return the longest common prefix among each and every strings present in the array. If there’s no prefix common in all the strings, return "". Examples: Input: arr[] = [“geeksforgeeks”, “geeks”, “geek”, “geezer”]Output: "gee"Explanation: "gee" is the l
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences