Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

176
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda