Show the index where the pattern first appears.
Acceptance criteria
- 1.#out should show at 6.
DSA Tutorial · Strings
These 10 tasks go with the String Matching: KMP and Rabin-Karp chapter. 5 of them ask you to build something small from scratch; 5 give you code that is already broken and ask you to work out why. Set aside about 90 minutes for the whole set, though you can do them in any order.
Nothing here is marked by a person. When you press Submit, the editor checks your code against the points listed under each task and tells you straight away what passed and what didn't (you need a free account to submit). If you get stuck, there are hints, and a worked solution once you've had a go. The first 2 tasks are free; the rest are part of the practice plan.
If it's been a while since you read the chapter, here is how it starts: “Searching for a substring is O(n × m) if you do the obvious thing. Two classic algorithms get it to O(n + m), each by never throwing away what the previous comparison already told you.” .
1.Find with indexOfexercise · easy · 10 min
Show the index where the pattern first appears.
Passes when: #out should show at 6.
2.Naive searchexercise · easy · 10 min · practice plan
Write a nested-loop search and show the index found.
Passes when: #out should show at 2.
3.Build a prefix tableexercise · easy · 10 min · practice plan
Build the KMP failure table for the pattern and join it.
Passes when: #out should show 0-0-1-2.
4.Count occurrencesexercise · easy · 10 min · practice plan
Count how many times the pattern appears, overlapping allowed.
Passes when: #out should show seen 2.
5.Report a missing patternexercise · medium · 10 min · practice plan
Show the word absent when the pattern is not present.
Passes when: #out should show absent.
6.Fix indexOf treated as a booleanbug fix · easy · 8 min
indexOf returns 0 for a match at the start, which is falsy.
Passes when: #out should show present.
7.Fix the search boundbug fix · easy · 8 min · practice plan
Looping to the full length reads past the end and never matches.
Passes when: #out should show at 2.
8.Fix the prefix table starting at zerobug fix · medium · 8 min · practice plan
The table's first entry is always 0, so the loop must start at one.
Passes when: #out should show 0-0-1-2.
9.Fix the non-overlapping countbug fix · easy · 8 min · practice plan
Skipping a whole pattern length misses overlapping matches.
Passes when: #out should show seen 2.
10.Fix the hash compared without confirmingbug fix · easy · 8 min · practice plan
Two different strings can share a hash, so a match must be confirmed character by character.
Passes when: #out should show rejected.
Between them these tasks cover Pattern search, Prefix function and Rolling hash.
Looking for a different chapter? See every practice set, or switch to the interview theory questions.