Given a string str of N characters, the task is to calculate the count of valid unordered pairs of (i, j) such that the string after deleting ith character is equal to the string after deleting the jth character.
Examples:
Input: str = “aabb”
Output: 2
Explanation: The string after deletion of 1st element is “abb” and the string after deletion of 2nd element is “abb”. Similarly, the string after deletion of 3rd element is “aab” and the string after deletion of 4th element is “aab”. Hence, the number of valid pairs of (i, j) are 2, i.e, (1, 2) and (3, 4).
Input: str = “aaaaaa”
Output: 15
Approach: The given problem can be solved using the following observations:
- If Si = Sj, then Si = Si+1 = Si+2 … = Sj must hold true.
- Also if Si = Sj, then str[i] = str[i+1] = str[i+2] … = str[j] must hold true as well.
Therefore, using the above observations, the two-pointer technique can be used to calculate the intervals (l, r) in the string str such that str[l] = str[l+1] … = str[r], and for each valid (l, r), the count of valid pairs will be r – lC2.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countValidPairs(string str, int N)
{
int ans = 0;
for ( int l = 0, r; l < N; l = r) {
r = l;
while (r < N && str[l] == str[r]) {
r++;
}
ans += ((r - l) * (r - l - 1)) / 2;
}
return ans;
}
int main()
{
string str = "aaaaaa" ;
cout << countValidPairs(str, str.length());
return 0;
}
|
Java
import java.util.*;
public class GFG
{
static int countValidPairs(String str, int N)
{
int ans = 0 ;
for ( int l = 0 , r; l < N; l = r) {
r = l;
Character c1 = str.charAt(l);
Character c2 = str.charAt(r);
while (r < N && c1.equals(c2)) {
r++;
}
ans += ((r - l) * (r - l - 1 )) / 2 ;
}
return ans;
}
public static void main(String args[])
{
String str = "aaaaaa" ;
System.out.print(countValidPairs(str, str.length()));
}
}
|
Python3
def countValidPairs( str , N):
ans = 0 ;
l = 0 ;
r = None ;
while (l < N):
r = l;
while (r < N and str [l] = = str [r]):
r + = 1
ans + = ((r - l) * (r - l - 1 )) / / 2 ;
l = r;
return ans;
str = "aaaaaa" ;
print (countValidPairs( str , len ( str )));
|
C#
using System;
class GFG
{
static int countValidPairs( string str, int N)
{
int ans = 0;
for ( int l = 0, r; l < N; l = r) {
r = l;
char c1 = str[l];
char c2 = str[r];
while (r < N && c1.Equals(c2)) {
r++;
}
ans += ((r - l) * (r - l - 1)) / 2;
}
return ans;
}
public static void Main()
{
string str = "aaaaaa" ;
Console.Write(countValidPairs(str, str.Length));
}
}
|
Javascript
<script>
function countValidPairs(str, N)
{
let ans = 0;
for (let l = 0, r; l < N; l = r) {
r = l;
while (r < N && str[l] == str[r]) {
r++;
}
ans += ((r - l) * (r - l - 1)) / 2;
}
return ans;
}
let str = "aaaaaa" ;
document.write(countValidPairs(str, str.length));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)