Here is the interview question prompt, presented for reference.
How would you write a function to detect a substring in a string?
If the substring can be found in the string, return the index at which it starts. Otherwise, return -1
.
function detectSubstring(str, subStr) {
return -1;
}
Important-- do not use the native String
class's built-in substring
or substr
method. This exercise is to understand the underlying implementation of that method.
100000
O(n)
O(1)
You can see the full challenge with visuals at this link.
Challenges • Asked over 4 years ago by Tonya Sims
This is the main discussion thread generated for Detect Substring In String.
Hi! I'm using Python and trying not to peek at the answer, but is using the find() method an efficient solution? Or should we something where we're keeping track of the indexes with pointers?
What is the point of keeping the variable idxOfStart if it is never used in the final solution?
Echoing Seth's comment, what's the use of the "idxOfStart" variable?
a='a cat in the hat'
b='hat'
start=0
end=int(len(a))
leap=int(len(b))
while start<=end:
if a[start:leap]==b:
print(start)
else:
start=start+1
leap=leap+1
I am using this code to find the substring in a string. It is working but going into an infinite loop. Can someone help me with what i am doing wrong?
Hey Kiran,
I formatted your code so it's easier to read:
a='a cat in the hat'
b='hat'
start=0
end=int(len(a))
leap=int(len(b))
while start<=end:
if a[start:leap]==b:
print(start)
else:
start=start+1
leap=leap+1
The problem seems to be the else
statement. Instead of adding 1
to both the start and leap, you want to add 1
to the start and subtract 1
from the end. That way you're moving the pointers closer together, getting closer to the start <= end
clause.
Question's test cases better to cover one more edge case..
python
def test_4(self):
assert detectSubstring("aaaaab", "aab") == 3
print(
"PASSED: `detectSubstring('aaaaab', 'aab')` should return `3`"
)
And some part of illustrative description is wrong.
3 X 6 = 12 how come? it should be 3 x 4 = 12