Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Number of substrings divisible by 6 in a string of integers
Next article icon

Number of even substrings in a string of digits

Last Updated : 26 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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

Recommended Practice
Count even substrings
Try It!

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   
?>
 
 
Output
6      

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
 
 
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.



Next Article
Number of substrings divisible by 6 in a string of integers

A

Anuj Chauhan
Improve
Article Tags :
  • DSA
  • Strings
  • divisibility
Practice Tags :
  • Strings

Similar Reads

  • Number of substrings divisible by 6 in a string of integers
    Given a string consisting of integers 0 to 9. The task is to count the number of substrings which when convert into integer are divisible by 6. Substring does not contain leading zeroes. Examples: Input : s = "606". Output : 5 Substrings "6", "0", "6", "60", "606" are divisible by 6. Input : s = "48
    9 min read
  • Number of substrings divisible by 4 in a string of integers
    Given a string consisting of integers 0 to 9. The task is to count the number of substrings which when converted into integer are divisible by 4. Substring may contain leading zeroes. Examples: Input : "124" Output : 4 Substrings divisible by 4 are "12", "4", "24", "124" . Input : "04" Output : 3 Su
    11 min read
  • Number of subsequences in a string divisible by n
    Given a string consisting of digits 0-9, count the number of subsequences in it divisible by m.Examples: Input : str = "1234", n = 4Output : 4The subsequences 4, 12, 24 and 124 are divisible by 4. Input : str = "330", n = 6Output : 4The subsequences 30, 30, 330 and 0 are divisible by n.Input : str =
    11 min read
  • Number of substrings with odd decimal value in a binary string
    Given a binary string containing only 0's and 1's. Write a program to find number of sub-strings of this string whose decimal representation is odd. Examples : Input : 101 Output : 3 Explanation : Substrings with odd decimal representation are: {1, 1, 101} Input : 1101 Output : 6 Explanation : Subst
    6 min read
  • Number of sub-strings in a given binary string divisible by 2
    Given binary string str of length N, the task is to find the count of substrings of str which are divisible by 2. Leading zeros in a substring are allowed. Examples: Input: str = "101" Output: 2 "0" and "10" are the only substrings which are divisible by 2. Input: str = "10010" Output: 10 Naive appr
    4 min read
  • XOR of all substrings of a given Binary String
    Given a binary string str of size N, the task is to calculate the bitwise XOR of all substrings of str. Examples: Input: str = "11"Output: 11Explanation: The substrings of "11" are: 1, 1, and 11.Their XOR = 1 ⊕ 1 ⊕ 11 = 11 Input: str = "110"Output: 111Explanation: The substrings of 110 are: 1, 1, 0,
    6 min read
  • Find the longest Substring of a given String S
    Given a string S of length, N. Find the maximum length of any substring of S such that, the bitwise OR of all the characters of the substring is equal to the bitwise OR of the remaining characters of the string. If no such substring exists, print -1. Examples: Input: S = "2347"Output: 3?Explanation:
    10 min read
  • Count of repeating digits in a given Number
    Given a number N, the task is to count the total number of repeating digits in the given number. Examples: Input: N = 99677 Output: 2Explanation:In the given number only 9 and 7 are repeating, hence the answer is 2. Input: N = 12Output: 0Explanation:In the given number no digits are repeating, hence
    12 min read
  • Number of subsequences in a given binary string divisible by 2
    Given binary string str of length N, the task is to find the count of subsequences of str which are divisible by 2. Leading zeros in a sub-sequence are allowed. Examples: Input: str = "101" Output: 2 "0" and "10" are the only subsequences which are divisible by 2.Input: str = "10010" Output: 22 Naiv
    4 min read
  • Form minimum number of Palindromic Strings from a given string
    Given a string S, the task is to divide the characters of S to form minimum number of palindromic strings. Note: There can be multiple correct answers. Examples: Input: S = "geeksforgeeks"Output: {eegksrskgee, o, f} Explanation: There should be at least 3 strings "eegksrskgee", "o", "f". All 3 forme
    12 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences