VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-substrings-with-same-first-and-last-characters/

⇱ Count substrings with same first and last characters - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count substrings with same first and last characters

Last Updated : 23 Jul, 2025

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.


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.

Output
7

Related Articles:

Comment