VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-string-substring-another/

⇱ Check if a string is substring of another - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if a string is substring of another

Last Updated : 17 Jan, 2026

Given two strings txt and pat, the task is to find if pat is a substring of txt. If yes, return the index of the first occurrence, else return -1.

Examples :

Input: txt= "geeksforgeeks", pat = "eks"
Output: 2
Explanation: String "eks" is present at index 2 and 10, so 2 is the smallest index.

Input: txt= "geeksforgeeks", pat = "xyz"
Output: -1.
Explanation: There is no occurrence of "xyz" in "geeksforgeeks"

Using nested loops - O(m*n) Time and O(1) Space

The basic idea is to iterate through a loop in the string txt and for every index in the string txt, check whether we can match pat starting from this index. This can be done by running a nested loop for traversing the string pat and checking for each character of pat matches with txt or not. If all character of pat matches then return the starting index of such substring.


Output
2

Time complexity: O(m * n) where m and n are lengths of txt and pat respectively. 
Auxiliary Space: O(1), as no extra space is required.

Using Pattern Searching Algorithms

There are several Pattern Searching Algorithms like KMP Algorithm, Rabin-Karp Algorithm, Aho-Corasick Algorithm, etc. Please refer to Introduction to Pattern Searching to learn more about them.

Using in-built library functions

This approach uses a built-in function to quickly check if pattern is part of text or not. This makes the process simple and efficient.


Output
2

Note: The time complexity of in-built functions can differ across different languages.

Comment
Article Tags:
Article Tags: