Number of even substrings in a string of digits
Last Updated :
23 Jul, 2025
Given a string of digits 0 - 9. The task is to count a number of substrings which when converting into integer form an even number.
Examples :
Input : str = "1234".
Output : 6
"2", "4", "12", "34", "234", "1234"
are 6 substring which are even.
Input : str = "154".
Output : 3
Input : str = "15".
Output : 0
For a number to be even, the substring must end with an even digit. We find all the even digits in the string and for each even digit, count the number of substrings ending with it. Now, observe that the number of substrings will be an index of that even digit plus one.
Implementation:
C++
// C++ program to count number of substring
// which are even integer in a string of digits.
#include<bits/stdc++.h>
using namespace std;
// Return the even number substrings.
int evenNumSubstring(char str[])
{
int len = strlen(str);
int count = 0;
for (int i = 0; i < len; i++)
{
int temp = str[i] - '0';
// If current digit is even, add
// count of substrings ending with
// it. The count is (i+1)
if (temp % 2 == 0)
count += (i + 1);
}
return count;
}
// Driven Program
int main()
{
char str[] = "1234";
cout << evenNumSubstring(str) << endl;
return 0;
}
Java
// Java program to count number of
// substring which are even integer
// in a string of digits.
public class GFG {
// Return the even number substrings.
static int evenNumSubstring(String str)
{
int len = str.length();
int count = 0;
for (int i = 0; i < len; i++)
{
int temp = str.charAt(i) - '0';
// If current digit is even, add
// count of substrings ending with
// it. The count is (i+1)
if (temp % 2 == 0)
count += (i + 1);
}
return count;
}
public static void main(String args[])
{
String str= "1234";
System.out.println(evenNumSubstring(str));
}
}
// This code is contributed by Sam007.
Python3
# Python 3 program to count number of substring
# which are even integer in a string of digits.
# Return the even number substrings.
def evenNumSubstring(str):
length = len(str)
count = 0
for i in range(0,length,1):
temp = ord(str[i]) - ord('0')
# If current digit is even, add
# count of substrings ending with
# it. The count is (i+1)
if (temp % 2 == 0):
count += (i + 1)
return count
# Driven Program
if __name__ == '__main__':
str = ['1','2','3','4']
print(evenNumSubstring(str))
# This code is contributed by
# Surendra_Gangwar
C#
// C# program to count number of
// substring which are even integer
// in a string of digits.
using System;
public class GFG {
// Return the even number substrings.
static int evenNumSubstring(string str)
{
int len = str.Length;
int count = 0;
for (int i = 0; i < len; i++)
{
int temp = str[i] - '0';
// If current digit is even,
// add count of substrings
// ending with it. The count
// is (i+1)
if (temp % 2 == 0)
count += (i + 1);
}
return count;
}
// Driver code
public static void Main()
{
string str= "1234";
Console.Write(
evenNumSubstring(str));
}
}
// This code is contributed by Sam007.
JavaScript
<script>
// Javascript program to count number of
// substring which are even integer
// in a string of digits.
// Return the even number substrings.
function evenNumSubstring(str)
{
let len = str.length;
let count = 0;
for (let i = 0; i < len; i++)
{
let temp = str[i] - '0';
// If current digit is even,
// add count of substrings
// ending with it. The count
// is (i+1)
if (temp % 2 == 0)
count += (i + 1);
}
return count;
}
let str= "1234";
document.write(evenNumSubstring(str));
</script>
PHP
<?php
// PHP program to count number
// of substring which are even
// integer in a string of digits.
// Return the even number substrings.
function evenNumSubstring($str)
{
$len = strlen($str);
$count = 0;
for ($i = 0; $i < $len; $i++)
{
$temp = $str[$i] - '0';
// If current digit is even, add
// count of substrings ending with
// it. The count is (i+1)
if ($temp % 2 == 0)
$count += ($i + 1);
}
return $count;
}
// Driver Code
$str = "1234";
echo evenNumSubstring($str),"\n" ;
// This code is contributed by jit_t
?>
Time Complexity: O(length of string).
This article is contributed by Anuj Chauhan.
Count Even and Odd Digits:
Approach:
Initialize variables e and o to 0, which will be used to count the number of even and odd digits in the string.
Loop through each character in the string s, and for each character:
a. Convert the character to an integer and check if it is even by taking its modulus with 2. If it is even, increment e by 1, otherwise increment o by 1.
Calculate the number of even and odd substrings using the formula (n*(n+1))/2, where n is the number of even or odd prefixes. This formula is derived from the fact that the number of substrings that can be formed from a string of length n is (n*(n+1))/2.
Add the number of even and odd substrings to get the total number of even substrings.
Return the total number of even substrings.
C++
#include <iostream>
#include <string>
using namespace std;
// Function to count the number of substrings with an even number of even digits
int count_even_substrings(string s) {
int n = s.length(); // Get the length of the input string
int e = 0; // Initialize a counter for even digits
// Loop through each character in the string
for (char c : s) {
// Check if the character is an even digit (0, 2, 4, 6, or 8)
if ((c - '0') % 2 == 0) {
e++; // Increment the even digit counter
}
}
int o = n - e; // Calculate the number of odd digits
// Calculate the total number of substrings with an even number of even digits
// by summing the combinations of substrings with even and odd digits
return (e * (e + 1) / 2) + (o * (o + 1) / 2);
}
int main() {
string s = "1234";
cout << count_even_substrings(s) << endl; // Output: 6
return 0;
}
Java
import java.util.Scanner;
public class Main {
// Function to count the number of substrings with an even number of even digits
static int countEvenSubstrings(String s) {
int n = s.length(); // Get the length of the input string
int e = 0; // Initialize a counter for even digits
// Loop through each character in the string
for (char c : s.toCharArray()) {
// Check if the character is an even digit (0, 2, 4, 6, or 8)
if ((c - '0') % 2 == 0) {
e++; // Increment the even digit counter
}
}
int o = n - e; // Calculate the number of odd digits
// Calculate the total number of substrings with an even number of even digits
// by summing the combinations of substrings with even and odd digits
return (e * (e + 1) / 2) + (o * (o + 1) / 2);
}
public static void main(String[] args) {
String s = "1234";
System.out.println(countEvenSubstrings(s)); // Output: 6
}
}
Python3
def count_even_substrings(s):
n = len(s)
e = sum(1 for c in s if int(c) % 2 == 0)
o = n - e
return (e*(e+1)//2) + (o*(o+1)//2)
s = "1234"
print(count_even_substrings(s)) # Output: 6
C#
using System;
class Program {
// Function to count the number of substrings with an
// even number of even digits
static int CountEvenSubstrings(string s)
{
int n = s.Length; // Get the length of the input
// string
int e = 0; // Initialize a counter for even digits
// Loop through each character in the string
foreach(char c in s)
{
// Check if the character is an even digit (0,
// 2, 4, 6, or 8)
if ((c - '0') % 2 == 0) {
e++; // Increment the even digit counter
}
}
int o = n - e; // Calculate the number of odd digits
// Calculate the total number of substrings with an
// even number of even digits by summing the
// combinations of substrings with even and odd
// digits
return (e * (e + 1) / 2) + (o * (o + 1) / 2);
}
static void Main()
{
string s = "1234";
Console.WriteLine(
CountEvenSubstrings(s)); // Output: 6
}
}
JavaScript
function count_even_substrings(s) {
// Get the length of the string
let n = s.length;
// Count the number of even digits in the string
let e = [...s].filter(c => parseInt(c) % 2 == 0).length;
// Calculate the number of odd digits in the string
let o = n - e;
// Return the sum of the number of substrings with an even number of even digits
// and the number of substrings with an odd number of even digits
return (e*(e+1)/2) + (o*(o+1)/2);
}
// Example usage
let s = "1234";
console.log(count_even_substrings(s)); // Output: 6
The time complexity of this algorithm is O(n), where n is the length of the input string s. This is because the algorithm iterates through the input string once to count the number of even and odd digits, and then performs two constant-time calculations to determine the number of even and odd substrings. The dominant operation in this algorithm is the iteration through the input string, which takes O(n) time.
The auxiliary space of this algorithm is O(1), because the algorithm only uses a constant amount of additional space to store the counts of even and odd digits. The amount of additional space used does not depend on the length of the input string. Therefore, the space complexity of this algorithm is constant.
Number of even substrings in a string of digits
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