Good morning! Here's our prompt for today.
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
.
JAVASCRIPT
1function detectSubstring(str, subStr) {
2 return -1;
3}
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.
Constraints
- Length of both the given strings <=
100000
- The strings would never be null
- The strings will only consist of lowercase letters
- Expected time complexity :
O(n)
- Expected space complexity :
O(1)
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
44
var assert = require('assert');
​
console.log('Running and logging statements.');
​
function detectSubstring(str, subStr) {
// Fill in this method
return str;
}
​
console.log(detectSubstring('ggraph', 'graph'));
console.log(detectSubstring('geography', 'graph'));
console.log(detectSubstring('digginn', 'inn'));
​
try {
assert.equal(detectSubstring('thepigflewwow', 'flew'), 6);
​
console.log(
'PASSED: ' + "`detectSubstring('thepigflewwow', 'flew')` should return `6`"
);
} catch (err) {
console.log(err);
}
​
try {
assert.equal(detectSubstring('twocanplay', 'two'), 0);
​
console.log(
'PASSED: ' + "`detectSubstring('twocanplay', 'two')` should return `0`"
);
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Tired of reading? Watch this video explanation!
To change the speed of the video or see it in full screen, click the icons to the right of the progress bar.

Here's how we would solve this problem...
How do I use this guide?