VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-of-sub-strings-of-length-n-possible-from-the-given-string/

⇱ Count of sub-strings of length n possible from the given string - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count of sub-strings of length n possible from the given string

Last Updated : 11 Jul, 2025

Given a string str and an integer N, the task is to find the number of possible sub-strings of length N.
Examples:

Input: str = "geeksforgeeks", n = 5 
Output:
All possible sub-strings of length 5 are "geeks", "eeksf", "eksfo", 
"ksfor", "sforg", "forge", "orgee", "rgeek" and "geeks".
Input: str = "jgec", N = 2 
Output:

Method 1:Naive Approach

Approach:

The approach used in this code is to iterate over all possible starting positions of a substring of length N in the given string str, and count the number of valid substrings. We can check if a substring is valid by using the substr function to extract a substring of length N starting from the current position, and checking if its length is equal to N.

Implementation:


Output
9

Time Complexity: O(M*N), where M is the length of the input string str, since we iterate over N possible starting positions and extract a substring of length N each time.
Auxiliary Space: O(1), no extra space is required.

Method 2:Efficient Approach

Approach: The count of sub-strings of length n will always be len - n + 1 where len is the length of the given string. For example, if str = "geeksforgeeks" and n = 5 then the count of sub-strings having length 5 will be "geeks", "eeksf", "eksfo", "ksfor", "sforg", "forge", "orgee", "rgeek" and "geeks" which is len - n + 1 = 13 - 5 + 1 = 9.
Below is the implementation of the above approach: 


Output
9

Time Complexity: O(1), it is a constant.
Auxiliary Space: O(1), no extra space is required.

Comment
Article Tags: