Open In App

Shortest substring of a string containing all given words

Improve
Improve
Like Article
Like
Save
Share
Report

Print the shortest sub-string of a string containing all the given words. In the first example, two solutions are possible: “world is here. this is a life full of ups” and “ups and downs. life is world”.

  1. Initialize HashMap with all the given words which are required to be searched and assign their values as -1.
  2. Maintain a counter.
  3. Traverse the entire String word by word and do following for each sentence word
    • If the sentence word exists in the list of words you’re looking for, update the last position of that word.
    • Increase the total count if the updated last position was not initialized.
    • If the total count is equal to count of all given words, loop through the last positions and find the smallest one. The distance between the current position and that value will be the length of the substring. Record these values and find the best one over all positions

Below is Java implementation of above steps. 

C++





Java





Python3





C#





Javascript





Output

ups and downs. life is world. 








Last Updated : 11 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads