Find the Index of the First Occurrence in a String – Solution & Complexity
1. Understand the Match Requirement
- Return the first index where
subappears insides. - If there is no matching position, return
-1. - If
subis empty, the conventional first occurrence is index0.
2. Try Each Possible Start Index
- A substring of length
mcan only start at indices0throughlen(s) - m. - For each start index, compare the next
mcharacters withsub. - The first full match is the answer.
3. Avoid Out-of-Bounds Checks
- Stop the loop at
len(s) - len(sub)so every checked slice has enough characters. - If
subis longer thans, the range is empty and the function returns-1. - This keeps the control flow simple.
4. Manual Character Comparison Option
- Slicing is concise, but you can also compare characters one by one.
- Stop early when a mismatch appears.
- This is the same basic brute-force string search idea.
5. Complete Solution and Complexity
- The final solution checks the empty substring case, then tests each possible starting position.
- Time complexity is O(n * m), where
nislen(s)andmislen(sub). - Space complexity is O(1), ignoring the temporary slice used for comparison.