DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Leetcode - 30. Substring with Concatenation of All Words

Javascript Code

/**
 * @param {string} s
 * @param {string[]} words
 * @return {number[]}
 */
var findSubstring = function (s, words) {
    if (!s || words.length == 0) return [];
    let wordMap = {};
    for (let word of words) {
        wordMap[word] = (wordMap[word] || 0) + 1
    }
    let eachWordSize = words[0].length;
    let numOfWords = words.length;
    let ans = [];

    for (let i = 0; i <= s.length - eachWordSize * numOfWords; i++) {
        let seen = {};
        let j = 0;
        while (j < numOfWords) {
            let currentWord = s.substring(i + j * eachWordSize, i + (j + 1) * eachWordSize);
            if (!wordMap[currentWord]) break;
            seen[currentWord] = (seen[currentWord] || 0) + 1;
            if (seen[currentWord] > wordMap[currentWord]) {
                break;
            }
            j++;
        }
        if (j == numOfWords) {
            ans.push(i)
        }
    }
    return ans
};

Enter fullscreen mode Exit fullscreen mode

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay