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
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Count substrings with k distinct characters
Next article icon

Count substrings with same first and last characters

Last Updated : 10 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a string s consisting of lowercase characters, the task is to find the count of all substrings that start and end with the same character.

Examples : 

Input : s = “abcab”
Output : 7
Explanation: The substrings are “a”, “abca”, “b”, “bcab”, “c”, “a”, “b”.

Input : s = “aba”
Output : 4
Explanation: The substrings are “a”, “aba”, “b”, and “a”.

[Naive Approach] Using Two Nested Loops – O(n^2) time and O(1) space

The idea is to check each possible substring in the string and count those that have the same first and last character.

C++
// C++ program to count all substrings with same // first and last characters. #include <bits/stdc++.h> using namespace std;  int countSubstring(string s) {     int count = 0;     int n = s.length();          // Consider all possible substrings     for (int i = 0; i < n; i++) {         for (int j = i; j < n; j++) {                          // If first and last characters             // of substring s[i..j] are same             if (s[i] == s[j]) {                 count++;             }         }     }          return count; }  int main() {     string s = "abcab";     cout << countSubstring(s);     return 0; } 
Java
// Java program to count all substrings with same // first and last characters.  class GfG {      static int countSubstring(String s) {         int count = 0;         int n = s.length();                  // Consider all possible substrings         for (int i = 0; i < n; i++) {             for (int j = i; j < n; j++) {                                  // If first and last characters                 // of substring s[i..j] are same                 if (s.charAt(i) == s.charAt(j)) {                     count++;                 }             }         }                  return count;     }      public static void main(String[] args) {         String s = "abcab";         System.out.println(countSubstring(s));     } } 
Python
# Python program to count all substrings with same # first and last characters.  def countSubstring(s):     count = 0     n = len(s)          # Consider all possible substrings     for i in range(n):         for j in range(i, n):                          # If first and last characters             # of substring s[i..j] are same             if s[i] == s[j]:                 count += 1          return count  if __name__ == "__main__":     s = "abcab"     print(countSubstring(s)) 
C#
// C# program to count all substrings with same // first and last characters. using System;  class GfG {      static int countSubstring(string s) {         int count = 0;         int n = s.Length;                  // Consider all possible substrings         for (int i = 0; i < n; i++) {             for (int j = i; j < n; j++) {                                  // If first and last characters                 // of substring s[i..j] are same                 if (s[i] == s[j]) {                     count++;                 }             }         }                  return count;     }      static void Main() {         string s = "abcab";         Console.WriteLine(countSubstring(s));     } } 
JavaScript
// JavaScript program to count all substrings with same // first and last characters.  function countSubstring(s) {     let count = 0;     let n = s.length;          // Consider all possible substrings     for (let i = 0; i < n; i++) {         for (let j = i; j < n; j++) {                          // If first and last characters             // of substring s[i..j] are same             if (s[i] === s[j]) {                 count++;             }         }     }          return count; }  let s = "abcab"; console.log(countSubstring(s)); 

Output
7

[Expected Approach] Using Character Frequency – O(n) time and O(1) space

The idea is to use the fact that for each character in the alphabet, we can directly calculate how many substrings would start and end with that character without actually generating all possible substrings. By counting the frequency of each character in the string, we can use the combination formula to determine how many ways we can select two occurrences of the same character to form the start and end of substrings, plus the substrings of length 1.

Step by step approach:

  1. Count the frequency of each lowercase letter in the input string.
  2. For each character that appears in the string, calculate the number of possible substrings using the formula n*(n+1)/2.
  3. Return the final sum as the total count of valid substrings.
C++
// C++ program to count all substrings with same // first and last characters. #include <bits/stdc++.h> using namespace std;  int countSubstring(string s) {     int n = s.length();          // Create an array to store      // frequency of characters     vector<int> freq(26, 0);          // Update frequency of each character     for (int i = 0; i < n; i++) {         freq[s[i] - 'a']++;     }          int count = 0;          // For each character, calculate number of substrings     // that start and end with that character     for (int i = 0; i < 26; i++) {                  // Number of substrings with same          // first and last character is          // nC2 + n = n*(n+1)/2         count += (freq[i] * (freq[i] + 1)) / 2;     }          return count; }  int main() {     string s = "abcab";     cout << countSubstring(s);     return 0; } 
Java
// Java program to count all substrings with same // first and last characters.  class GfG {      static int countSubstring(String s) {         int n = s.length();                  // Create an array to store          // frequency of characters         int[] freq = new int[26];                  // Update frequency of each character         for (int i = 0; i < n; i++) {             freq[s.charAt(i) - 'a']++;         }                  int count = 0;                  // For each character, calculate number of substrings         // that start and end with that character         for (int i = 0; i < 26; i++) {                          // Number of substrings with same              // first and last character is              // nC2 + n = n*(n+1)/2             count += (freq[i] * (freq[i] + 1)) / 2;         }                  return count;     }      public static void main(String[] args) {         String s = "abcab";         System.out.println(countSubstring(s));     } } 
Python
# Python program to count all substrings with same # first and last characters.  def countSubstring(s):     n = len(s)          # Create an array to store      # frequency of characters     freq = [0] * 26          # Update frequency of each character     for i in range(n):         freq[ord(s[i]) - ord('a')] += 1          count = 0          # For each character, calculate number of substrings     # that start and end with that character     for i in range(26):                  # Number of substrings with same          # first and last character is          # nC2 + n = n*(n+1)/2         count += (freq[i] * (freq[i] + 1)) // 2          return count  if __name__ == "__main__":     s = "abcab"     print(countSubstring(s)) 
C#
// C# program to count all substrings with same // first and last characters. using System;  class GfG {      static int countSubstring(string s) {         int n = s.Length;                  // Create an array to store          // frequency of characters         int[] freq = new int[26];                  // Update frequency of each character         for (int i = 0; i < n; i++) {             freq[s[i] - 'a']++;         }                  int count = 0;                  // For each character, calculate number of substrings         // that start and end with that character         for (int i = 0; i < 26; i++) {                          // Number of substrings with same              // first and last character is              // nC2 + n = n*(n+1)/2             count += (freq[i] * (freq[i] + 1)) / 2;         }                  return count;     }      static void Main() {         string s = "abcab";         Console.WriteLine(countSubstring(s));     } } 
JavaScript
// JavaScript program to count all substrings with same // first and last characters.  function countSubstring(s) {     let n = s.length;          // Create an array to store      // frequency of characters     let freq = new Array(26).fill(0);          // Update frequency of each character     for (let i = 0; i < n; i++) {         freq[s.charCodeAt(i) - 'a'.charCodeAt(0)]++;     }          let count = 0;          // For each character, calculate number of substrings     // that start and end with that character     for (let i = 0; i < 26; i++) {                  // Number of substrings with same          // first and last character is          // nC2 + n = n*(n+1)/2         count += (freq[i] * (freq[i] + 1)) / 2;     }          return count; }  let s = "abcab"; console.log(countSubstring(s)); 

Output
7

Related Articles:

  • Recursive solution to count substrings with same first and last characters
  • Count substrings with different first and last characters


Next Article
Count substrings with k distinct characters

A

Aditya Gupta
Improve
Article Tags :
  • DSA
  • Mathematical
  • Strings
  • Technical Scripter
  • Amazon
Practice Tags :
  • Amazon
  • Mathematical
  • Strings

Similar Reads

  • Count substrings with different first and last characters
    Given a string S, the task is to print the count of substrings from a given string whose first and last characters are different. Examples: Input: S = "abcab"Output: 8Explanation: There are 8 substrings having first and last characters different {ab, abc, abcab, bc, bca, ca, cab, ab}. Input: S = "ab
    10 min read
  • Recursive solution to count substrings with same first and last characters
    We are given a string S, we need to find count of all contiguous substrings starting and ending with same character. Examples : Input : S = "abcab" Output : 7 There are 15 substrings of "abcab" a, ab, abc, abca, abcab, b, bc, bca bcab, c, ca, cab, a, ab, b Out of the above substrings, there are 7 su
    11 min read
  • Count substrings with k distinct characters
    Given a string consisting of lowercase characters and an integer k, the task is to count all possible substrings (not necessarily distinct) that have exactly k distinct characters. Examples: Input: s = "abc", k = 2Output: 2Explanation: Possible substrings are {"ab", "bc"} Input: s = "aba", k = 2Outp
    10 min read
  • Count K-Length Substrings With No Repeated Characters
    Given a string S and an integer k, the task is to return the number of substrings in S of length k with no repeated characters. Example: Input: S = "geeksforgeeks", k = 5Output: 4Explanation: There are 4 substrings, they are: 'eksfo', 'ksfor', 'sforg', 'forge'. Input: S = "home", k = 5Output: 0Expla
    6 min read
  • Number of substrings with count of each character as k
    Given a string and an integer k, find the number of substrings in which all the different characters occur exactly k times. Examples: Input : s = "aabbcc" k = 2 Output : 6 The substrings are aa, bb, cc, aabb, bbcc and aabbcc. Input : s = "aabccc" k = 2 Output : 3 There are three substrings aa, cc an
    15 min read
  • Count substrings made up of a single distinct character
    Given a string S of length N, the task is to count the number of substrings made up of a single distinct character.Note: For the repetitive occurrences of the same substring, count all repetitions. Examples: Input: str = "geeksforgeeks"Output: 15Explanation: All substrings made up of a single distin
    5 min read
  • Count of substrings having all distinct characters
    Given a string str consisting of lowercase alphabets, the task is to find the number of possible substrings (not necessarily distinct) that consists of distinct characters only.Examples: Input: Str = "gffg" Output: 6 Explanation: All possible substrings from the given string are, ( "g", "gf", "gff",
    7 min read
  • Count number of substrings having at least K distinct characters
    Given a string S consisting of N characters and a positive integer K, the task is to count the number of substrings having at least K distinct characters. Examples: Input: S = "abcca", K = 3Output: 4Explanation:The substrings that contain at least K(= 3) distinct characters are: "abc": Count of dist
    7 min read
  • Count of substrings of a given Binary string with all characters same
    Given binary string str containing only 0 and 1, the task is to find the number of sub-strings containing only 1s and 0s respectively, i.e all characters same. Examples: Input: str = “011”Output: 4Explanation: Three sub-strings are "1", "1", "11" which have only 1 in them, and one substring is there
    10 min read
  • Count of all unique substrings with non-repeating characters
    Given a string str consisting of lowercase characters, the task is to find the total number of unique substrings with non-repeating characters. Examples: Input: str = "abba" Output: 4 Explanation: There are 4 unique substrings. They are: "a", "ab", "b", "ba". Input: str = "acbacbacaa" Output: 10 App
    6 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