VOOZH about

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

⇱ Count substrings with different first and last characters - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count substrings with different first and last characters

Last Updated : 15 Jul, 2025

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: 8
Explanation: 
There are 8 substrings having first and last characters different {ab, abc, abcab, bc, bca, ca, cab, ab}.

Input: S = "aba"
Output: 2
Explanation: 
There are 2 substrings having first and last characters different {ab, ba}.

Naive Approach: The idea is to generate all possible substrings of a given string and for each substring, check if the first and the last characters are different or not. If found to be true, then increment the count by 1 and check for the next substring. Print the count after traversal of all the substring.

Below is the implementation of the above approach:


Output: 
8

Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: The above approach can be optimized using Map by to store the frequency of the characters of the string. Follow the steps below to solve the problem:

  1. Initialize two variables, one for counting different characters for every iteration (say cur) and one to store the final count of substrings (say ans).
  2. Initialize a map M to store the frequency of all characters in it.
  3. Traverse the given string and for each character, follow the steps below:
    • Iterate the map M.
    • If the first element i.e., the key of the map is not the same as the current character, then proceed.
    • Otherwise, add the value corresponding to the current character.
  4. After traversal of the Map, add cur to the final result i.e., ans += cur.

Below is the implementation of the above approach:


Output: 
8

Time Complexity: O(N*26)
Auxiliary Space: O(N)


 

Comment