Skip to content
Related Articles

Related Articles

Find all words from String present after given N words

View Discussion
Improve Article
Save Article
  • Last Updated : 20 Sep, 2022
View Discussion
Improve Article
Save Article

Given a string S and a list lis[] of N number of words, the task is to find every possible (N+1)th word from string S such that the ‘second’ word comes immediately after the ‘first’ word, the ‘third’ word comes immediately after the ‘second’ word, the ‘fourth’ word comes immediately after the ‘third’ word and so on.

Examples:

Input: S = “Siddhesh is a smart guy the city he lives in is a smart city”, lis: [“is”, “a”, “smart”]
Output: [guy, city]
Explanation: Here the two sequences where the words occur
just as the pattern mentioned are.

  • is a smart guy
  • is a smart city

Hence we found ‘guy’ and ‘city’ as the desired words. 

Input: S = “David loves to play and David loves to write sometimes”, lis: [“loves”, “to”]
Output: [play, write] 

Approach: The simplest way to solve the problem is:

Break the whole string into words separated by spaces and Iterate over these words and match (i)th, (i+1)th, . . . (i+N-1)th word with the first, second, . . ., Nth words given, If the words matched store the (i+N)th word in a list.    

Follow the steps to solve the problem:

  • Split the given string S by spaces. 
  • Create a list ‘res‘ to store the ‘N+1’th words in the string.
  • Now, iterate through the split string from i = 0. 
    • Check every (i)th, (i+1)th, . . ., (i+N-1)th indices in every iteration, whether they are equal to the ‘first’, ‘second’, . . ., ‘N’th words respectively or not. 
    • If yes then append the (N+1)th word to the answer list.
  • Return the list storing the words as the required answer.

Below is the implementation for the above idea:

C++




// C++ program for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
vector<string> findOcurrences(string s, vector<string>& lis)
{
 
    // Split the given string
    // by default split function splits the
    // string by spaces and stores the
    // splited words in a list
    vector<string> temp_lis;
    string temp_str = "";
    for (int i = 0; i < s.size(); ++i) {
        if (s[i] == ' ') {
            temp_lis.push_back(temp_str);
            temp_str = "";
        }
        else
            temp_str += s[i];
    }
    if (temp_str != "")
        temp_lis.push_back(temp_str);
 
    vector<string> res;
    int N = lis.size();
 
    // Loop to find the matching string
    // and the last word
    string join_lis = "";
    for (auto str : lis)
        join_lis += str;
 
    for (int i = 0; i < temp_lis.size() - N; ++i) {
        string join_temp_lis = "";
        for (int j = i; j < i + N; ++j)
            join_temp_lis += temp_lis[j];
        if (join_lis == join_temp_lis)
            res.push_back(temp_lis[i + N]);
    }
    // Return the answer list
    return res;
}
 
// Driver code
int main()
{
    string s = "Siddhesh is a smart guy the city he lives "
               "in is a smart city";
    vector<string> lis = { "is", "a", "smart" };
 
    // Function call
    vector<string> final_list = findOcurrences(s, lis);
 
    for (auto st : final_list)
        cout << st << " ";
 
    return 0;
}
 
    // This code is contributed by rakeshsahni

Java




/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.*;
 
class GFG {
 
  public static ArrayList<String>
    findOcurrences(String s, ArrayList<String> lis)
  {
 
    // Split the given string
    // by default split function splits the
    // string by spaces and stores the
    // splited words in a list
    ArrayList<String> temp_lis
      = new ArrayList<String>();
    String temp_str = "";
    for (int i = 0; i < s.length(); ++i) {
      if (s.charAt(i) == ' ') {
        temp_lis.add(temp_str);
        temp_str = "";
      }
      else
        temp_str += s.charAt(i);
    }
    if (temp_str != "")
      temp_lis.add(temp_str);
 
    ArrayList<String> res = new ArrayList<String>();
    int N = lis.size();
 
    // Loop to find the matching string
    // and the last word
    String join_lis = "";
    for (int str = 0; str < lis.size(); str++)
      join_lis += lis.get(str);
 
    for (int i = 0; i < temp_lis.size() - N; ++i) {
      String join_temp_lis = new String();
      for (int j = i; j < i + N; ++j)
        join_temp_lis += temp_lis.get(j);
      if (join_lis.equals(join_temp_lis))
        res.add(temp_lis.get(i + N));
    }
    return res;
  }
 
  public static void main(String[] args)
  {
    String s
      = "Siddhesh is a smart guy the city he lives in is a smart city";
    ArrayList<String> lis = new ArrayList<String>();
    lis.add("is");
    lis.add("a");
    lis.add("smart");
     
    // Function call
    System.out.println(findOcurrences(s, lis));
  }
}
 
// This code is contributed by akashish__

Python3




# Python program for the above approach:
 
def findOcurrences(string, lis):
   
    # Split the given string
    # by default split function splits the
    # string by spaces and stores the
    # splited words in a list
    temp_lis = string.split()
    res = []
    N = len(lis)
     
    # Loop to find the matching string
    # and the last word
    for i in range(len(temp_lis)-N):
        if ''.join(lis) == ''.join(temp_lis[i:i + N]):
            res.append(temp_lis[i + N])
     
    # Return the answer list
    return res
 
# Driver code
if __name__ == '__main__':
    string = "Siddhesh is a smart guy the city he lives in is a smart city"
    lis = ["is", "a", "smart"]
     
    # Function call
    final_list = findOcurrences(string, lis)
    print(final_list)

C#




using System;
using System.Collections.Generic;
 
public class GFG {
 
  public static string findOcurrences(string s,
                                      string[] lis)
  {
 
    // Split the given string
    // by default split function splits the
    // string by spaces and stores the
    // splited words in a list
    List<string> temp_lis = new List<string>();
    string temp_str = "";
    for (int i = 0; i < s.Length; ++i) {
      if (s[i] == ' ') {
        temp_lis.Add(temp_str);
        temp_str = "";
      }
      else
        temp_str += s[i];
    }
    if (temp_str != "")
      temp_lis.Add(temp_str);
 
    List<string> res = new List<string>();
    int N = lis.Length;
 
    // Loop to find the matching string
    // and the last word
    string join_lis = "";
    for (int str = 0; str < lis.Length; str++)
      join_lis += lis[str];
 
    for (int i = 0; i < temp_lis.Count - N; ++i) {
      string join_temp_lis = "";
      for (int j = i; j < i + N; ++j)
        join_temp_lis += temp_lis[j];
      if (join_lis == join_temp_lis)
        res.Add(temp_lis[i + N]);
    }
    // Return the answer list
    return string.Join(" ", res);
  }
 
  static public void Main()
  {
 
    // Code
    string s
      = "Siddhesh is a smart guy the city he lives in is a smart city";
    string[] lis = { "is", "a", "smart" };
 
    // Function call
    string final_list = (findOcurrences(s, lis));
 
    for (int st = 0; st < final_list.Length; st++)
      Console.Write(final_list[st]);
  }
}
 
// This code is contributed by akashish__

Javascript




<script>
    // Javascript program for the above approach:
function findOcurrences(string, lis)
 
    // Split the given string
    // by default split function splits the
    // string by spaces and stores the
    // splited words in a list
    let temp_lis = string.split(" ");
    let res = [];
    let N = lis.length;
     
    // Loop to find the matching string
    // and the last word
    for(let i=0;i<temp_lis.length-N;i++)
    {
         
        if(lis.join('') == temp_lis.slice(i,i+N).join(''))
        {
            res.push(temp_lis[i+N]);
        }
    }
     
    // Return the answer list
    return res;
}
 
// Driver code
let string = "Siddhesh is a smart guy the city he lives in is a smart city";
let lis = ["is", "a", "smart"];
 
// Function call
let final_list = findOcurrences(string, lis);
console.log(final_list);
 
// This code is contributed by akashish__
</script>

Output

['guy', 'city']

Time Complexity: O(N * K * d) where K is the size of the string and d is the maximum size of a word
Auxiliary Space: O(N)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!