R

E

A

C

T

O

xamples 

epeat

ode

pproach

ptimize

est

indexOf

The Question

Implement the indexOf method for strings.

 

The indexOf method takes a “haystack” string, and a “needle” string to search for.

 

So, indexOf(“hello world”, “or”) would return 7.

 

 

The Approach

 

  • We're looking for a solution with O(mn) time. m being the length of the haystack string and n being the length of the needle. 
  • Loop over the haystack and for every character in the string, loop over the needle (inner loop) and check if the subsequent characters in the haystack match up with the corresponding characters in needle.
  • If it does then return the index where you began looking. 
  • If there is no match - return -1 
  • Remember - indexOf is case sensitive. 

 

Solutions:

https://repl.it/EOW4


A slightly less verbose implementation:

https://repl.it/EOWZ





Can we do better?

There are some really interesting algorithms that do this in O(m + k) time (the Knuth–Morris–Pratt Algorithm). Watch this video for more information

https://www.youtube.com/watch?v=GTJr8OvyEVQ

Copy of indexOf

By tessaslides

Copy of indexOf

Technical interview practice problem

  • 946