Back to course home
0% completed
Vote For New Content
Correct O(n × wordLength) where n = string length Solution
Kushak Zohaad Jafry
Jan 23, 2026
class Solution { findWordConcatenation(str, words) { const resultIndices = []; const wordLen = words[0].length; const numWords = words.length; const totalLen = wordLen * numWords; // TODO: Write your code here let wordsFreqMap = new Map(); for(let i=0; i<words.length; i++) { wordsFreqMap.set(words[i], (wordsFreqMap.get(words[i]) || 0) + 1); } const uniqueWordsToMatch = wordsFreqMap.size; for (let offset = 0; offset < wordLen; offset++) { let windowStart = offset; let windowEnd = offset; let wordsMatched = 0; const currWordsCount = new Map(); while(windowEnd + wordLen <= str.length) { const currWord = str.substring(windowEnd, windowEnd + wordLen); windowEnd += wordLen; if(wordsFreqMap.has(currWord)) { currWordsCount.set(currWord, (currWordsCount.get(currWord) || 0) + 1); if(currWordsCount.get(currWord) === wordsFreqMap.get(currWord)) { wordsMatched++; }else if(currWordsCount.get(currWord) === wordsFreqMap.get(currWord) + 1) { wordsMatched--; } } if(windowEnd - windowStart > totalLen) { const startWord = str.substring(windowStart, windowStart + wordLen); windowStart += wordLen; if(wordsFreqMap.has(startWord)) { if(currWordsCount.get(startWord) === wordsFreqMap.get(startWord)) { wordsMatched--; }else if(currWordsCount.get(startWord) === wordsFreqMap.get(startWord) + 1) { wordsMatched++; } currWordsCount.set(startWord, currWordsCount.get(startWord) - 1); } } if(wordsMatched === uniqueWordsToMatch) { resultIndices.push(windowStart); } } } return resultIndices; } }
0
0