Write a Python program to return an array of the starting indices of all concatenated substrings in the given string. Input: string = '123456876456123987', words = ['123','456']. Output: [0,9]. Explanation: The substring starting at 0 is '123456'. It is the concatenation of ['123','456'] which is a permutation of words. The substring starting at 9 is '456123'. It is the concatenation of ['456','123'] which is a permutation of words.
💡 Model Answer
The problem is a classic sliding‑window search for all permutations of a list of words. Each word has the same length, so the total length of a concatenated substring is len(words) * word_len. We slide a window of that size over the string, maintaining a frequency map of the words seen in the current window. If the map matches the target word frequency map, we record the start index.
Algorithm:
- Compute
word_lenandtotal_len. - Build a dictionary
needcounting each word inwords. - For each possible start index
ifrom 0 tolen(s)-total_len:
- Initialize an empty dictionary
seen. - For each word position
jin the window (0 tolen(words)-1):
Extract the word. * Incrementw = s[i + jword_len : i + (j+1)*word_len]seen[w]. * Ifseen[w]exceedsneed[w], break early.
- After the inner loop, if
seen == need, appendito result.
- Return the result list.
Complexity: We examine each window in O(m) time where m is the number of words. The outer loop runs O(n) times, so total time is O(n*m). Space usage is O(k) for the hash maps, where k is the number of distinct words.
Python code:
from collections import Counter
def find_concat_indices(s, words):
if not s or not words:
return []
word_len = len(words[0])
total_len = word_len * len(words)
need = Counter(words)
res = []
for i in range(len(s) - total_len + 1):
seen = Counter()
for j in range(len(words)):
w = s[i + j*word_len : i + (j+1)*word_len]
seen[w] += 1
if seen[w] > need[w]:
break
else:
if seen == need:
res.append(i)
return res
print(find_concat_indices('123456876456123987', ['123','456']))
# Output: [0, 9]This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.
Get Assisting AI — Starts at ₹500