My solution was very simple in Python:
if needle in haystack: return haystack.find(needle) else: return -1
Am I missing the point of the problem? This ran in 42 ms.
Let's compare to the following code:
It's a good when u used "in" before "find", this reduce the time if test cases contains more unmatched cases (i.e needle not in haystack), but it might slower if the test cases contains more matched cases (i.e needle in haystack)
However, since this is for practicing for interview, using built-in method is not a good way. We should practice code boyer-moore algorithm ^_^
Well , I did something similar too (ie) used the str.find() inbuilt function... and sort of feeling bad about it . The whole point of these exercises is to make you think how those functions might have been implemented. Try re-implementing this in C ( or in python without using the inbuilt functions)