Count of sub-strings that do not consist of the given character
Last Updated :
09 May, 2023
Given a string str and a character c. The task is to find the number of sub-strings that do not consist of the character c.
Examples:
Input: str = "baa", c = 'b'
Output: 3
The sub-strings are "a", "a" and "aa" Input: str = "ababaa", C = 'b'
Output: 5
Approach: Initially take a counter that counts the number of characters continuously with no character c. Iterate in the string and increase the counter till str[i] != c. Once str[i] == c, the number of sub-strings from the contiguous length cnt will be (cnt * (cnt + 1)) / 2. After the complete traversal of the string also add (cnt *(cnt + 1)) / 2 to the result for the group of characters appearing after the last occurrence of c.
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 number
// of sub-strings that do not contain
// the given character c
int countSubstrings(string s, char c)
{
// Length of the string
int n = s.length();
int cnt = 0;
int sum = 0;
// Traverse in the string
for (int i = 0; i < n; i++) {
// If current character is different
// from the given character
if (s[i] != c)
cnt++;
else {
// Update the number of sub-strings
sum += (cnt * (cnt + 1)) / 2;
// Reset count to 0
cnt = 0;
}
}
// For the characters appearing
// after the last occurrence of c
sum += (cnt * (cnt + 1)) / 2;
return sum;
}
// Driver code
int main()
{
string s = "baa";
char c = 'b';
cout << countSubstrings(s, c);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to return the number
// of sub-strings that do not contain
// the given character c
static int countSubstrings(String s, char c)
{
// Length of the string
int n = s.length();
int cnt = 0;
int sum = 0;
// Traverse in the string
for (int i = 0; i < n; i++)
{
// If current character is different
// from the given character
if (s.charAt(i) != c)
cnt++;
else
{
// Update the number of sub-strings
sum += (cnt * (cnt + 1)) / 2;
// Reset count to 0
cnt = 0;
}
}
// For the characters appearing
// after the last occurrence of c
sum += (cnt * (cnt + 1)) / 2;
return sum;
}
// Driver code
public static void main(String[] args)
{
String s = "baa";
char c = 'b';
System.out.println(countSubstrings(s, c));
}
}
// This code is contributed by Code_Mech.
Python3
# Python3 implementation of the approach
# Function to return the number
# of sub-strings that do not contain
# the given character c
def countSubstrings(s, c):
# Length of the string
n = len(s)
cnt = 0
Sum = 0
# Traverse in the string
for i in range(n):
# If current character is different
# from the given character
if (s[i] != c):
cnt += 1
else:
# Update the number of sub-strings
Sum += (cnt * (cnt + 1)) // 2
# Reset count to 0
cnt = 0
# For the characters appearing
# after the last occurrence of c
Sum += (cnt * (cnt + 1)) // 2
return Sum
# Driver code
s = "baa"
c = 'b'
print(countSubstrings(s, c))
# This code is contributed
# by mohit kumar
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the number
// of sub-strings that do not contain
// the given character c
static int countSubstrings(string s, char c)
{
// Length of the string
int n = s.Length;
int cnt = 0;
int sum = 0;
// Traverse in the string
for (int i = 0; i < n; i++)
{
// If current character is different
// from the given character
if (s[i] != c)
cnt++;
else
{
// Update the number of sub-strings
sum += (cnt * (cnt + 1)) / 2;
// Reset count to 0
cnt = 0;
}
}
// For the characters appearing
// after the last occurrence of c
sum += (cnt * (cnt + 1)) / 2;
return sum;
}
// Driver code
public static void Main()
{
string s = "baa";
char c = 'b';
Console.Write(countSubstrings(s, c));
}
}
// This code is contributed by Akanksha Rai
PHP
<?php
// PHP implementation of the approach
// Function to return the number
// of sub-strings that do not contain
// the given character c
function countSubstrings($s, $c)
{
// Length of the string
$n = strlen($s);
$cnt = 0;
$sum = 0;
// Traverse in the string
for ($i = 0; $i < $n; $i++)
{
// If current character is different
// from the given character
if ($s[$i] != $c)
$cnt++;
else
{
// Update the number of sub-strings
$sum += floor(($cnt * ($cnt + 1)) / 2);
// Reset count to 0
$cnt = 0;
}
}
// For the characters appearing
// after the last occurrence of c
$sum += floor(($cnt * ($cnt + 1)) / 2);
return $sum;
}
// Driver code
$s = "baa";
$c = 'b';
echo countSubstrings($s, $c);
// This code is contributed by Ryuga
?>
JavaScript
<script>
// javascript implementation of the approach
// Function to return the number
// of sub-strings that do not contain
// the given character c
function countSubstrings( s, c) {
// Length of the string
var n = s.length;
var cnt = 0;
var sum = 0;
// Traverse in the string
for (i = 0; i < n; i++) {
// If current character is different
// from the given character
if (s.charAt(i) != c)
cnt++;
else {
// Update the number of sub-strings
sum += (cnt * (cnt + 1)) / 2;
// Reset count to 0
cnt = 0;
}
}
// For the characters appearing
// after the last occurrence of c
sum += (cnt * (cnt + 1)) / 2;
return sum;
}
// Driver code
var s = "baa";
var c = 'b';
document.write(countSubstrings(s, c));
// This code contributed by umadevi9616
</script>
Time Complexity: O(n) where n is the length of the string
Auxiliary Space: O(1)
New Approach:- Here an alternative approach to count the number of substrings that do not contain a given character in a string
- Initialize a counter variable to 0.
- Initialize two pointers, start and end, to 0.
- Find the length of the string and store it in the variable n.
- Traverse the string using the end pointer until it reaches the end of the string.
- If the current character is equal to the given character, calculate the number of substrings that do not contain the given character using the formula (end - start) * (end - start + 1) / 2, and add it to the counter variable.
- Reset the start pointer to the next character after the current character.
- Increment the end pointer.
- Calculate the number of substrings that do not contain the given character for the remaining characters in the string, and add it to the counter variable.
- Return the final count.
- In the main function, initialize the input string and character, call the countSubstrings function, store the returned value in a variable, and print it.
Here's the implementation of the above approach in Java:
C++
#include <iostream>
#include <string>
using namespace std;
// This function takes a string s and a character c, and
// counts the number of substrings of s that contain c.
int countSubstrings(string s, char c)
{
int count
= 0; // The number of substrings that contain c
int start
= 0; // The start index of the current substring
int end = 0; // The end index of the current substring
int n = s.length(); // The length of the string s
// Loop through the string s
while (end < n) {
// If we find the character c, then we have a new
// substring that contains c.
if (s[end] == c) {
// We add the number of substrings that end at
// the previous index (end-1), plus the new
// substring that ends at the current index
// (end).
count += (end - start) * (end - start + 1) / 2;
// We update the start index to be the next
// index after the current index (end+1).
start = end + 1;
}
// We move the end index to the next character in
// the string.
end++;
}
// At the end of the loop, we need to add the remaining
// substrings that end at the last index (n-1).
count += (end - start) * (end - start + 1) / 2;
// Return the final count of substrings that contain c.
return count;
}
int main()
{
string s = "baa"; // The input string
char c = 'b'; // The character to look for in substrings
int count = countSubstrings(
s, c); // Count the substrings that contain c
cout << count << endl; // Print the final count
return 0;
}
// This code is contributed by sarojmcy2e
Java
public class Solution {
public static void main(String[] args) {
String s = "baa";
char c = 'b';
int count = countSubstrings(s, c);
System.out.println(count);
}
public static int countSubstrings(String s, char c) {
int count = 0;
int start = 0;
int end = 0;
int n = s.length();
while (end < n) {
if (s.charAt(end) == c) {
count += (end - start) * (end - start + 1) / 2;
start = end + 1;
}
end++;
}
count += (end - start) * (end - start + 1) / 2;
return count;
}
}
Python3
def countSubstrings(s, c):
count = 0
start = 0
end = 0
n = len(s)
while end < n:
if s[end] == c:
count += (end - start) * (end - start + 1) // 2
start = end + 1
end += 1
count += (end - start) * (end - start + 1) // 2
return count
s = "baa"
c = 'b'
count = countSubstrings(s, c)
print(count)
C#
using System;
class Program {
// This function takes a string s and a character c, and
// counts the number of substrings of s that contain c.
static int CountSubstrings(string s, char c)
{
int count
= 0; // The number of substrings that contain c
int start
= 0; // The start index of the current substring
int end
= 0; // The end index of the current substring
int n = s.Length; // The length of the string s
// Loop through the string s
while (end < n) {
// If we find the character c, then we have a
// new substring that contains c.
if (s[end] == c) {
// We add the number of substrings that end
// at the previous index (end-1), plus the
// new substring that ends at the current
// index (end).
count += (end - start) * (end - start + 1)
/ 2;
// We update the start index to be the next
// index after the current index (end+1).
start = end + 1;
}
// We move the end index to the next character
// in the string.
end++;
}
// At the end of the loop, we need to add the
// remaining substrings that end at the last index
// (n-1).
count += (end - start) * (end - start + 1) / 2;
// Return the final count of substrings that contain
// c.
return count;
}
static void Main(string[] args)
{
string s = "baa"; // The input string
char c = 'b'; // The character to look for in
// substrings
int count = CountSubstrings(
s, c); // Count the substrings that contain c
Console.WriteLine(count); // Print the final count
}
}
JavaScript
function countSubstrings(s, c) {
let count = 0; // The number of substrings that contain c
let start = 0; // The start index of the current substring
let end = 0; // The end index of the current substring
const n = s.length; // The length of the string s
// Loop through the string s
while (end < n) {
// If we find the character c, then we have a
// new substring that contains c.
if (s[end] === c) {
// We add the number of substrings that end
// at the previous index (end-1), plus the
// new substring that ends at the current
// index (end).
count += ((end - start) * (end - start + 1)) / 2;
// We update the start index to be the next
// index after the current index (end+1).
start = end + 1;
}
// We move the end index to the next character
// in the string.
end++;
}
// At the end of the loop, we need to add the
// remaining substrings that end at the last index
// (n-1).
count += ((end - start) * (end - start + 1)) / 2;
// Return the final count of substrings that contain
// c.
return count;
}
const s = "baa"; // The input string
const c = "b"; // The character to look for in substrings
const count = countSubstrings(s, c); // Count the substrings that contain c
console.log(count); // Print the final count
In this code, added the main method and used it to test the countSubstrings method by passing the input values s and c. The countSubstrings method is the same as the given code, which counts the number of substrings in the string s that do not contain the character c.
Time Complexity: The time complexity of the given code is O(n), where n is the length of the string s. This is because we are traversing the string s only once using the end pointer and performing constant-time operations in the while loop.
Auxiliary Space: The auxiliary space required by the given code is O(1), which is constant space. This is because we are not using any additional data structures or arrays to store the intermediate results, and all the calculations are done using the existing variables.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem