Find the starting indices of the substrings in string ( S ) which is made by concatenating all words from a list ( L ) | Java program to calculate the starting indices of substrings inside S which contains all the words present in List L . ; Returns an integer vector consisting of starting indices of substrings present inside the string S ; Number of a characters of a word in list L . ; Number of words present inside list L . ; Total characters present in list L . ; Resultant vector which stores indices . ; If the total number of characters in list L is more than length of string S itself . ; Map stores the words present in list L against it 's occurrences inside list L  ; Traverse the substring ; Extract the word ; If word not found or if frequency of current word is more than required simply break . ; Else decrement the count of word from hash_map ; Store the starting index of that substring when all the words in the list are in substring ; Driver code
import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashMap ; import java . util . List ; class GFG { public static ArrayList < Integer > findSubstring ( String A , final List < String > B ) { int size_word = B . get ( 0 ) . length ( ) ; int word_count = B . size ( ) ; int size_l = size_word * word_count ; ArrayList < Integer > res = new ArrayList < Integer > ( ) ; int n = A . length ( ) ; if ( size_l > n ) { return res ; } HashMap < String , Integer > hashMap = new HashMap < String , Integer > ( ) ; for ( String word : B ) { hashMap . put ( word , hashMap . getOrDefault ( word , 0 ) + 1 ) ; } for ( int i = 0 ; i <= n - size_l ; i ++ ) { HashMap < String , Integer > tempMap = ( HashMap < String , Integer > ) hashMap . clone ( ) ; int j = i , count = word_count ; while ( j < i + size_l ) { String word = A . substring ( j , j + size_word ) ; if ( ! hashMap . containsKey ( word ) || tempMap . get ( word ) == 0 ) { break ; } else { tempMap . put ( word , tempMap . get ( word ) - 1 ) ; count -- ; } j += size_word ; } if ( count == 0 ) { res . add ( i ) ; } } return res ; } public static void main ( String [ ] args ) { String S = " barfoothefoobarman " ; ArrayList < String > L = new ArrayList < > ( Arrays . asList ( " foo " , " bar " ) ) ; ArrayList < Integer > indices = findSubstring ( S , L ) ; for ( Integer i : indices ) { System . out . println ( i ) ; } } }