Detect Substring in String (Medium)

Good afternoon! Here's our prompt for today.

You may see this problem at Cisco, Autodesk, Salesforce, Zillow, Dropbox, Yelp, Databricks, Mailchimp, Samsara, Pipedrive, Grammarly, Digitalocean, Opendoor, and Docusign.

How would you write a function to detect a substring in a string?

Description

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)
JAVASCRIPT
OUTPUT
Results will appear here.