3

I have implemented the naive String search problem but I want to know what can be the alternate way to solve this algorithm ?

Here is my example :-

function naiveSearch(long, short) {
    let count = 0;
    for (let i=0;i<long.length;i++) {
        for(let j=0;j<short.length;j++) {
            if (short[j] !== long[i+j])
            break;
        if (j === short.length - 1)
        count++;
        }
    }
    return count;
}

As you can see the Time Complexity of this code is O(n ^ 2) as i have used the nested loop. So what can be the another way to solve this algorithm which will reduced the Time complexity ?

3
  • 1
    Boyer-Moore Commented Dec 23, 2019 at 14:47
  • 1
    en.wikipedia.org/wiki/String-searching_algorithm Commented Dec 23, 2019 at 14:48
  • Thanks @Ry- for the reference, I understood the cases of naive search algorithm Commented Dec 23, 2019 at 15:03

2 Answers 2

3

Naive search is inefficient by definition:

From wikipedia:

A simple and inefficient way to see where one string occurs inside another is to check each place it could be, one by one, to see if it's there

In JS there are simpler and more readable solution as:

function checkOccurrencies(string, stringToBeFound) {
  let counter = 0; 
  let found = string.indexOf(stringToBeFound, 0);

  while(found !== -1){
    counter += 1;  // Update number of match
    found = string.indexOf(stringToBeFound, found+1);  // Update found with next occurrence check
  }
  return counter;
}

console.log(checkOccurrencies("aababbajackasdasdjackasdhasdjack", "jack"));

Here are some benchmark with naive implementation vs indexOf It seems that the latter is also the more performant.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much -Mosè Raguzzini
1

const Naivesearch = (string, pattern) =>{
  const patternLength = pattern.length;
  let count = 0;
  if(string.length > patternLength){
    for(i=0; i<string.length; i++){
      let final = string.substring(i, patternLength+i);
      if(final === pattern) count = count+1 ;
    }
    return count;
  }
  else return count
}


console.log(Naivesearch("akgjfjhuyutomatokajkhgsvkjrtomato", "tomato"))

const Naivesearch = (string, pattern) =>{
  const patternLength = pattern.length;
  let count = 0;
  if(string.length > patternLength){
    for(i=0; i<string.length; i++){
      let final = string.substring(i, patternLength+i);
      if(final === pattern) count = count+1 ;
    }
    return count;
  }
  else return count
}

console.log(performance.now())
console.log(Naivesearch("akgjfjhuyutomatokajkhgsvkjrtomato", "tomato"))
console.log(performance.now())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.