Count of sub-strings of length n possible from the given string
Last Updated :
31 Aug, 2023
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
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:
C++
#include <bits/stdc++.h>
using namespace std;
int count_substrings(string str, int n) {
int count = 0;
for (int i = 0; i <= str.length() - n; i++) {
string substring = str.substr(i, n);
// check if the current substring has length n
if (substring.length() == n) {
count++;
}
}
return count;
}
int main() {
string str = "geeksforgeeks";
int n = 5;
cout << count_substrings(str, n) << endl;
return 0;
}
Java
public class CountSubstrings {
public static int countSubstrings(String str, int n) {
int count = 0;
for (int i = 0; i <= str.length() - n; i++) {
String substring = str.substring(i, i + n);
// check if the current substring has length n
if (substring.length() == n) {
count++;
}
}
return count;
}
public static void main(String[] args) {
String str = "geeksforgeeks";
int n = 5;
System.out.println(countSubstrings(str, n));
}
}
Python3
def count_substrings(string, n):
count = 0
for i in range(len(string) - n + 1):
substring = string[i:i+n]
# check if the current substring has length n
if len(substring) == n:
count += 1
return count
str = "geeksforgeeks"
n = 5
print(count_substrings(str, n))
C#
using System;
class GFG
{
// Function to count the number of substrings of length n in a given string.
static int CountSubstrings(string str, int n)
{
int count = 0;
// Loop through the string starting from index 0 and going up to length - n.
for (int i = 0; i <= str.Length - n; i++)
{
// Get the substring of length n starting at index i.
string substring = str.Substring(i, n);
// Check if the current substring has length n.
if (substring.Length == n)
{
count++;
}
}
return count;
}
static void Main()
{
string str = "geeksforgeeks";
int n = 5;
// Call the function to count substrings and print the result.
Console.WriteLine(CountSubstrings(str, n));
}
}
JavaScript
//Javascript Code
function count_substrings(str, n) {
let count = 0;
for (let i = 0; i <= str.length - n; i++) {
let substring = str.substr(i, n);
// check if the current substring has length n
if (substring.length === n) {
count++;
}
}
return count;
}
//Driver's Code
let str = "geeksforgeeks";
let n = 5;
console.log(count_substrings(str, n));
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:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the count of
// possible sub-strings of length n
int countSubStr(string str, int n)
{
int len = str.length();
return (len - n + 1);
}
// Driver code
int main()
{
string str = "geeksforgeeks";
int n = 5;
cout << countSubStr(str, n);
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class GFG
{
// Function to return the count of
// possible sub-strings of length n
static int countSubStr(String str, int n)
{
int len = str.length();
return (len - n + 1);
}
// Driver code
public static void main(String args[])
{
String str = "geeksforgeeks";
int n = 5;
System.out.print(countSubStr(str, n));
}
}
// This code is contributed by mohit kumar 29
Python3
# Python3 implementation of the approach
# Function to return the count of
# possible sub-strings of length n
def countSubStr(string, n) :
length = len(string);
return (length - n + 1);
# Driver code
if __name__ == "__main__" :
string = "geeksforgeeks";
n = 5;
print(countSubStr(string, n));
# This code is contributed by Ryuga
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the count of
// possible sub-strings of length n
static int countSubStr(string str, int n)
{
int len = str.Length;
return (len - n + 1);
}
// Driver code
public static void Main()
{
string str = "geeksforgeeks";
int n = 5;
Console.WriteLine(countSubStr(str, n));
}
}
// This code is contributed by Code_Mech.
JavaScript
<script>
// JavaScript implementation of the approach
// Function to return the count of
// possible sub-strings of length n
function countSubStr(str, n) {
var len = str.length;
return len - n + 1;
}
// Driver code
var str = "geeksforgeeks";
var n = 5;
document.write(countSubStr(str, n));
</script>
PHP
<?php
// PHP implementation of the approach
// Function to return the count of
// possible sub-strings of length n
function countSubStr($str, $n)
{
$len = strlen($str);
return ($len - $n + 1);
}
// Driver code
$str = "geeksforgeeks";
$n = 5;
echo(countSubStr($str, $n));
// This code is contributed by Code_Mech.
?>
Time Complexity: O(1), it is a constant.
Auxiliary Space: O(1), no extra space is required.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read