Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find the index of a substring

Return the first index where a substring appears in a string, or -1 if not present.

Python practice6 minString PatternsBeginnerLast updated March 18, 2026

Problem statement

Write a function find_substring_index(s, sub) that returns the index of the first occurrence of substring sub in string s. If sub is not found, return -1. If sub is an empty string, return 0 (the position where an empty substring is considered to occur). Do not use print; return the integer index.

Task

Implement a function to locate the first occurrence of a substring inside a string with expected behavior for empty substrings and non-matches.

Examples

Basic occurrence

Input

find_substring_index('hello', 'll')

Output

2

The substring 'll' starts at index 2 in 'hello'.

Input format

A call to find_substring_index(s, sub) where s and sub are strings.

Output format

An integer index (or -1) returned by the function.

Constraints

Do not use any external libraries. You may use built-in string methods. Time complexity should be O(n*m) in the worst case (where n and m are lengths of s and sub).

Samples

Sample 1

Input

find_substring_index('abc', 'a')

Output

0

'a' occurs at index 0.

Sample 2

Input

find_substring_index('abc', 'z')

Output

-1

'z' is not present, so return -1.