Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
Find indices within a string where any combination of an array of words is found

Sample data: String: "barfoofoobarthefoobarman" Array of words: ["bar", "foo", "the"]

Output: [6, 9, 12]

I was asked this question during an interview. Due to time constraint, I tried to find all the possible words that could be made out of the array of words (i. e. "barfoothe"), but was told that would not scale for large arrays. Was suggested to use a map data structure, but I think my solution doesn't scale either, and it's brute forced.

Here's the solution.

var solution = function(string, words) {
    let output = [];
    let wordsMap = new Map();
    let wordsNumber = words.length;
    let wordLength = words[0].length;
    words.forEach((word) => {
        if (!wordsMap.has(word))
            wordsMap.set(word, 1);
        else
            wordsMap.set(word, wordsMap.get(word) + 1);
    });        
 
    for (let i = 0; i <= string.length-(wordsNumber*wordLength); i+=wordLength) {
        let tempMap = new Map(wordsMap);
        let check = true;
        let tempString = string.substring(i, i + wordsNumber*wordLength);
        for (let j = 0; j <= tempString.length - wordLength; j += wordLength) {
            let tempString2 = tempString.substring(j, j + wordLength);
            if (tempMap.has(tempString2))
                tempMap.set(tempString2, tempMap.get(tempString2) - 1);
        }
        for (let val of tempMap.values()){
            if (val !== 0){
                check = false
                break;
            }
        }
        
        if (check)
            output.push(i)
    }
    console.log(output);        
}

solution("barfoothefoobarman", ["foo", "bar"]);

Any suggestion for a smarter solution?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You could create a dynamic regular expression.

const words = ['foo', 'bar']
const rx = new RegExp(words.join('|'), 'g') 
// todo escape special characters

Then search away.

const counts = words.map(it=>0) // [0,0]
// todo use map or object to track counts instead of array
while (m = rx.exec(inputString)) {
  const index = words.indexOf(m[0])
  counts[index]++
}
about 4 years ago · Juan Pablo Isaza Report

0

Thank you for your question. I think the question in the interview was less about the right solution and more about the right approach.

The trickiest part is actually just finding the word combinations. There are several approaches here. For me it's a clear case for recursion.

So my approach would be:

  1. find all word combinations, except combinations with itself (for example: foofoo or barbar).
  2. iterate through the word combinations and ask whether they are contained in the string.
  3. extra: Sort SolutionArray Done!

Note: I use indexOf() for point 2 but I think a regex match would make it even better because you find all possibilities of a word in a string and not just the first one like with indexOf. Would make sense for longer strings.

    const arr = ["foo", "bar"];
    const str = "barfoothefoobarman" 
    let res = [];
    const combinations = (len, val, existing) => {    
       if (len == 0) {
          res.push(val);
          return;
       }
      
       for(let i=0; i<arr.length; i++) {
          if(! existing[i]) {
             existing[i] = true;
             combinations(len-1, val + arr[i], existing);         
             existing[i] = false;
          } 
       }
    }

    const buildCombinations = (arr = []) => {
       for(let i = 0; i < arr.length; i++) {
          combinations(arr.length - i, "", []);      
       }
    };

    buildCombinations(arr);

    // exclude the base wordes from result array
    newRes = res.filter((e) => {  
      if (! arr.includes(e)) {    
        return e;
      } 
    })
    
    console.log('all word combinations:', newRes);

    // get the string position
    const _positions = [];
    newRes.forEach((w) => {
      let res = str.indexOf(w);      
      if (res != -1 && ! _positions.includes(res)) {
          _positions.push(res);  
      }  
    })

    // sort array and use Float64Array to speed up
    const positions = new Float64Array(_positions)
    console.log('positions', positions.sort())

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!