AlgoMaster Logo

Substring with Concatenation of All Words

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

The simplest approach is to generate all possible substrings of the given string s that can be formed with the total length of all the words. For each substring, check if the substring is a valid concatenation of the words in the given word list with the help of permutations. If it is, record the starting index.

Steps:

  1. Calculate the total length of all words combined: substring_length = words.length * word_length.
  2. Iterate over each substring of s with length substring_length.
  3. For each substring, generate all permutations of the word list.
  4. Check if any permutation matches the substring.
  5. If a match is found, store the starting index of the substring.

Code:

2. Sliding Window with HashMap

Intuition:

Instead of generating permutations, we can use a sliding window with the help of a hashmap to keep track of the word count. This allows us to efficiently check if the current sliding window contains a valid concatenation of the words.

Steps:

  1. Create a hashmap wordCount containing the frequency of each word.
  2. Iterate over s in a sliding window where the step is the word length.
  3. For each starting position, initialize a new hashmap seenWords to count words in the current window.
  4. Slide over the segment, counting words, and if the window is invalid (i.e., a word is missing, or we have too many of a word), reset and start from the next word boundary.
  5. If the window is valid (i.e., all word counts match), add the starting index to the result.

Code: