![]() |
VOOZH | about |
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: 9
All possible sub-strings of length 5 are "geeks", "eeksf", "eksfo",
"ksfor", "sforg", "forge", "orgee", "rgeek" and "geeks".
Input: str = "jgec", N = 2
Output: 3
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:
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.
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:
9
Time Complexity: O(1), it is a constant.
Auxiliary Space: O(1), no extra space is required.