Count new pairs of strings that can be obtained by swapping first characters of pairs of strings from given array
Last Updated :
02 Jul, 2021
Given an array arr[] consisting of N strings, the task is to find the pair of strings that is not present in the array formed by any pairs (arr[i], arr[j]) by swapping the first characters of the strings arr[i] and arr[j].
Examples:
Input: arr[] = {“good”, “bad”, “food”}
Output: 2
Explanation:
The possible pairs that can be formed by swapping the first characters of any pair are:
- (“good”, “bad”): Swapping the characters ‘g’ and ‘b’, modifies the strings to “bood” and gad which is not present in the array.
- (“bad”, “food”): Swapping the characters ‘g’ and ‘b’, modifies the strings to “bood” and gad which is not present in the array.
Therefore, the total count is 2.
Input: arr[] = {“geek”, “peek”}
Output: 0
Naive Approach: The simplest approach to solve the given problem is to generate all the pairs of strings and for each pair swap the first characters of both the strings and if both the strings are present in the array then count this pair. After checking for all the pairs, print the value of the count obtained.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void countStringPairs(string a[], int n)
{
int ans = 0;
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++) {
string p = a[i], q = a[j];
if (p[0] != q[0]) {
swap(p[0], q[0]);
int flag1 = 0;
int flag2 = 0;
for ( int k = 0; k < n; k++) {
if (a[k] == p) {
flag1 = 1;
}
if (a[k] == q) {
flag2 = 1;
}
}
if (flag1 == 0 && flag2 == 0) {
ans = ans + 1;
}
}
}
}
cout << ans;
}
int main()
{
string arr[] = { "good" , "bad" , "food" };
int N = sizeof (arr) / sizeof (arr[0]);
countStringPairs(arr, N);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG{
static void countStringPairs(String a[], int n)
{
int ans = 0 ;
for ( int i = 0 ; i < n; i++)
{
for ( int j = i + 1 ; j < n; j++)
{
char p[] = a[i].toCharArray();
char q[] = a[j].toCharArray();
if (p[ 0 ] != q[ 0 ])
{
char temp = p[ 0 ];
p[ 0 ] = q[ 0 ];
q[ 0 ] = temp;
int flag1 = 0 ;
int flag2 = 0 ;
for ( int k = 0 ; k < n; k++)
{
if (a[k].equals( new String(p)))
{
flag1 = 1 ;
}
if (a[k].equals( new String(q)))
{
flag2 = 1 ;
}
}
if (flag1 == 0 && flag2 == 0 )
{
ans = ans + 1 ;
}
}
}
}
System.out.println(ans);
}
public static void main(String[] args)
{
String arr[] = { "good" , "bad" , "food" };
int N = arr.length;
countStringPairs(arr, N);
}
}
|
Python3
def countStringPairs(a, n):
ans = 0
for i in range (n):
for j in range (i + 1 , n, 1 ):
p = a[i]
q = a[j]
if (p[ 0 ] ! = q[ 0 ]):
p = list (p)
q = list (q)
temp = p[ 0 ]
p[ 0 ] = q[ 0 ]
q[ 0 ] = temp
p = ''.join(p)
q = ''.join(q)
flag1 = 0
flag2 = 0
for k in range (n):
if (a[k] = = p):
flag1 = 1
if (a[k] = = q):
flag2 = 1
if (flag1 = = 0 and flag2 = = 0 ):
ans = ans + 1
print (ans)
if __name__ = = '__main__' :
arr = [ "good" , "bad" , "food" ]
N = len (arr)
countStringPairs(arr, N)
|
C#
using System;
class GFG {
static void countStringPairs( string [] a, int n)
{
int ans = 0;
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++) {
char [] p = a[i].ToCharArray();
char [] q = a[j].ToCharArray();
if (p[0] != q[0]) {
char temp = p[0];
p[0] = q[0];
q[0] = temp;
int flag1 = 0;
int flag2 = 0;
for ( int k = 0; k < n; k++) {
if (a[k].Equals( new string (p))) {
flag1 = 1;
}
if (a[k].Equals( new string (q))) {
flag2 = 1;
}
}
if (flag1 == 0 && flag2 == 0) {
ans = ans + 1;
}
}
}
}
Console.WriteLine(ans);
}
public static void Main( string [] args)
{
string [] arr = { "good" , "bad" , "food" };
int N = arr.Length;
countStringPairs(arr, N);
}
}
|
Javascript
<script>
function countStringPairs(a, n) {
var ans = 0;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
var p = a[i];
var q = a[j];
if (p[0] !== q[0]) {
p = p.split( "" );
q = q.split( "" );
var temp = p[0];
p[0] = q[0];
q[0] = temp;
p = p.join( "" );
q = q.join( "" );
var flag1 = 0;
var flag2 = 0;
for (let k = 0; k < n; k++) {
if (a[k] === p) flag1 = 1;
if (a[k] === q) flag2 = 1;
}
if (flag1 === 0 && flag2 === 0) {
ans = ans + 1;
}
}
}
}
document.write(ans);
}
var arr = [ "good" , "bad" , "food" ];
var N = arr.length;
countStringPairs(arr, N);
</script>
|
Time Complexity: O(N3)
Auxiliary Space: O(M), where M is the largest size of the string present in the array, A[]
Efficient Approach: The above approach can also be optimized by using the concept of Hashing. Follow the steps below to solve the problem:
- Initialize a variable, say ans as 0 to store the possible count of pairs of strings.
- Initialize a HashMap, say M to store all the strings present in the array arr[].
- Traverse the array, arr[] and increment the occurrence of arr[i] in M.
- Iterate in the range [0, N – 1] using the variable i and perform the following steps:
- After completing the above steps, print the value of ans as the result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void countStringPairs(string a[], int n)
{
int ans = 0;
unordered_map<string, int > s;
for ( int i = 0; i < n; i++) {
s[a[i]]++;
}
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++) {
string p = a[i];
string q = a[j];
if (p[0] != q[0]) {
swap(p[0], q[0]);
if (s.find(p) == s.end()
&& s.find(q) == s.end()) {
ans++;
}
}
}
}
cout << ans;
}
int main()
{
string arr[] = { "good" , "bad" , "food" };
int N = sizeof (arr) / sizeof (arr[0]);
countStringPairs(arr, N);
return 0;
}
|
Java
import java.lang.*;
import java.util.*;
class GFG{
static void countStringPairs(String a[], int n)
{
int ans = 0 ;
Map<String, Integer> s = new HashMap<>();
for ( int i = 0 ; i < n; i++)
{
s.put(a[i], s.getOrDefault(a[i], 0 ));
}
for ( int i = 0 ; i < n; i++)
{
for ( int j = i + 1 ; j < n; j++)
{
StringBuilder p = new StringBuilder(a[i]);
StringBuilder q = new StringBuilder(a[j]);
if (p.charAt( 0 ) != q.charAt( 0 ))
{
char t = p.charAt( 0 );
p.setCharAt( 0 , q.charAt( 0 ));
q.setCharAt( 0 , t);
if (!s.containsKey(p.toString()) &&
!s.containsKey(q.toString()))
{
ans++;
}
}
}
}
System.out.println(ans);
}
public static void main(String[] args)
{
String arr[] = { "good" , "bad" , "food" };
int N = arr.length;
countStringPairs(arr, N);
}
}
|
Python3
def countStringPairs(a, n):
ans = 0
s = {}
for i in range (n):
s[a[i]] = s.get(a[i], 0 ) + 1
for i in range (n):
for j in range (i + 1 , n):
p = [i for i in a[i]]
q = [j for j in a[j]]
if (p[ 0 ] ! = q[ 0 ]):
p[ 0 ], q[ 0 ] = q[ 0 ], p[ 0 ]
if (("".join(p) not in s) and
("".join(q) not in s)):
ans + = 1
print (ans)
if __name__ = = '__main__' :
arr = [ "good" , "bad" , "food" ]
N = len (arr)
countStringPairs(arr, N)
|
Javascript
<script>
function countStringPairs(a, n)
{
let ans = 0;
let s = new Map();
for (let i = 0; i < n; i++)
{
if (!s.has(a[i]))
s.set(a[i],0);
s.set(a[i], s.get(a[i]) + 1);
}
for (let i = 0; i < n; i++)
{
for (let j = i + 1; j < n; j++)
{
let p = (a[i]).split( "" );
let q = (a[j]).split( "" );
if (p[0] != q[0])
{
let t = p[0];
p[0] = q[0];
q[0] = t;
if (!s.has(p.join( "" )) &&
!s.has(q.join( "" )))
{
ans++;
}
}
}
}
document.write(ans);
}
let arr=[ "good" , "bad" , "food" ];
let N = arr.length;
countStringPairs(arr, N);
</script>
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
static void countStringPairs( string [] a, int n)
{
int ans = 0;
Dictionary< string , int > s = new Dictionary< string , int >();
for ( int i = 0; i < n; i++)
{
if (!s.ContainsKey(a[i]))
s.Add(a[i],0);
s[a[i]]++;
}
for ( int i = 0; i < n; i++)
{
for ( int j = i + 1; j < n; j++)
{
char [] p = (a[i]).ToCharArray();
char [] q = (a[j]).ToCharArray();
if (p[0] != q[0])
{
char t = p[0];
p[0]=q[0];
q[0]=t;
if (!s.ContainsKey( new string (p)) &&
!s.ContainsKey( new string (q)))
{
ans++;
}
}
}
}
Console.WriteLine(ans);
}
static public void Main ()
{
string [] arr = { "good" , "bad" , "food" };
int N = arr.Length;
countStringPairs(arr, N);
}
}
|
Time Complexity: O(N2)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...