![]() |
VOOZH | about |
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:
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:
Below is the implementation of the above approach:
8
Time Complexity: O(N*26)
Auxiliary Space: O(N)