Pairs of complete strings in two sets of strings
Last Updated :
14 Apr, 2023
Two strings are said to be complete if on concatenation, they contain all the 26 English alphabets. For example, "abcdefghi" and "jklmnopqrstuvwxyz" are complete as they together have all characters from 'a' to 'z'.
We are given two sets of sizes n and m respectively and we need to find the number of pairs that are complete on concatenating each string from set 1 to each string from set 2.
Input : set1[] = {"abcdefgh", "geeksforgeeks",
"lmnopqrst", "abc"}
set2[] = {"ijklmnopqrstuvwxyz",
"abcdefghijklmnopqrstuvwxyz",
"defghijklmnopqrstuvwxyz"}
Output : 7
The total complete pairs that are forming are:
"abcdefghijklmnopqrstuvwxyz"
"abcdefghabcdefghijklmnopqrstuvwxyz"
"abcdefghdefghijklmnopqrstuvwxyz"
"geeksforgeeksabcdefghijklmnopqrstuvwxyz"
"lmnopqrstabcdefghijklmnopqrstuvwxyz"
"abcabcdefghijklmnopqrstuvwxyz"
"abcdefghijklmnopqrstuvwxyz"
Method 1 (Naive method): A simple solution is to consider all pairs of strings, concatenate them and then check if the concatenated string has all the characters from 'a' to 'z' by using a frequency array.
Implementation:
C++
// C++ implementation for find pairs of complete
// strings.
#include <iostream>
using namespace std;
// Returns count of complete pairs from set[0..n-1]
// and set2[0..m-1]
int countCompletePairs(string set1[], string set2[],
int n, int m)
{
int result = 0;
// Consider all pairs of both strings
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// Create a concatenation of current pair
string concat = set1[i] + set2[j];
// Compute frequencies of all characters
// in the concatenated string.
int frequency[26] = { 0 };
for (int k = 0; k < concat.length(); k++)
frequency[concat[k] - 'a']++;
// If frequency of any character is not
// greater than 0, then this pair is not
// complete.
int i;
for (i = 0; i < 26; i++)
if (frequency[i] < 1)
break;
if (i == 26)
result++;
}
}
return result;
}
// Driver code
int main()
{
string set1[] = { "abcdefgh", "geeksforgeeks",
"lmnopqrst", "abc" };
string set2[] = { "ijklmnopqrstuvwxyz",
"abcdefghijklmnopqrstuvwxyz",
"defghijklmnopqrstuvwxyz" };
int n = sizeof(set1) / sizeof(set1[0]);
int m = sizeof(set2) / sizeof(set2[0]);
cout << countCompletePairs(set1, set2, n, m);
return 0;
}
Java
// Java implementation for find pairs of complete
// strings.
class GFG {
// Returns count of complete pairs from set[0..n-1]
// and set2[0..m-1]
static int countCompletePairs(String set1[], String set2[],
int n, int m)
{
int result = 0;
// Consider all pairs of both strings
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// Create a concatenation of current pair
String concat = set1[i] + set2[j];
// Compute frequencies of all characters
// in the concatenated String.
int frequency[] = new int[26];
for (int k = 0; k < concat.length(); k++) {
frequency[concat.charAt(k) - 'a']++;
}
// If frequency of any character is not
// greater than 0, then this pair is not
// complete.
int k;
for (k = 0; k < 26; k++) {
if (frequency[k] < 1) {
break;
}
}
if (k == 26) {
result++;
}
}
}
return result;
}
// Driver code
static public void main(String[] args)
{
String set1[] = { "abcdefgh", "geeksforgeeks",
"lmnopqrst", "abc" };
String set2[] = { "ijklmnopqrstuvwxyz",
"abcdefghijklmnopqrstuvwxyz",
"defghijklmnopqrstuvwxyz" };
int n = set1.length;
int m = set2.length;
System.out.println(countCompletePairs(set1, set2, n, m));
}
}
// This code is contributed by PrinciRaj19992
Python3
# Python3 implementation for find pairs of complete
# strings.
# Returns count of complete pairs from set[0..n-1]
# and set2[0..m-1]
def countCompletePairs(set1,set2,n,m):
result = 0
# Consider all pairs of both strings
for i in range(n):
for j in range(m):
# Create a concatenation of current pair
concat = set1[i] + set2[j]
# Compute frequencies of all characters
# in the concatenated String.
frequency = [0 for i in range(26)]
for k in range(len(concat)):
frequency[ord(concat[k]) - ord('a')] += 1
# If frequency of any character is not
# greater than 0, then this pair is not
# complete.
k = 0
while(k<26):
if (frequency[k] < 1):
break
k += 1
if (k == 26):
result += 1
return result
# Driver code
set1=["abcdefgh", "geeksforgeeks", "lmnopqrst", "abc"]
set2=["ijklmnopqrstuvwxyz", "abcdefghijklmnopqrstuvwxyz", "defghijklmnopqrstuvwxyz"]
n = len(set1)
m = len(set2)
print(countCompletePairs(set1, set2, n, m))
# This code is contributed by shinjanpatra
C#
// C# implementation for find pairs of complete
// strings.
using System;
class GFG {
// Returns count of complete pairs from set[0..n-1]
// and set2[0..m-1]
static int countCompletePairs(string[] set1, string[] set2,
int n, int m)
{
int result = 0;
// Consider all pairs of both strings
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// Create a concatenation of current pair
string concat = set1[i] + set2[j];
// Compute frequencies of all characters
// in the concatenated String.
int[] frequency = new int[26];
for (int k = 0; k < concat.Length; k++) {
frequency[concat[k] - 'a']++;
}
// If frequency of any character is not
// greater than 0, then this pair is not
// complete.
int l;
for (l = 0; l < 26; l++) {
if (frequency[l] < 1) {
break;
}
}
if (l == 26) {
result++;
}
}
}
return result;
}
// Driver code
static public void Main()
{
string[] set1 = { "abcdefgh", "geeksforgeeks",
"lmnopqrst", "abc" };
string[] set2 = { "ijklmnopqrstuvwxyz",
"abcdefghijklmnopqrstuvwxyz",
"defghijklmnopqrstuvwxyz" };
int n = set1.Length;
int m = set2.Length;
Console.Write(countCompletePairs(set1, set2, n, m));
}
}
// This article is contributed by Ita_c.
JavaScript
<script>
// Javascript implementation for find pairs of complete
// strings.
// Returns count of complete pairs from set[0..n-1]
// and set2[0..m-1]
function countCompletePairs(set1,set2,n,m)
{
let result = 0;
// Consider all pairs of both strings
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
// Create a concatenation of current pair
let concat = set1[i] + set2[j];
// Compute frequencies of all characters
// in the concatenated String.
let frequency = new Array(26);
for(let i= 0;i<26;i++)
{
frequency[i]=0;
}
for (let k = 0; k < concat.length; k++) {
frequency[concat[k].charCodeAt(0) - 'a'.charCodeAt(0)]++;
}
// If frequency of any character is not
// greater than 0, then this pair is not
// complete.
let k;
for (k = 0; k < 26; k++) {
if (frequency[k] < 1) {
break;
}
}
if (k == 26) {
result++;
}
}
}
return result;
}
// Driver code
let set1=["abcdefgh", "geeksforgeeks",
"lmnopqrst", "abc"];
let set2=["ijklmnopqrstuvwxyz",
"abcdefghijklmnopqrstuvwxyz",
"defghijklmnopqrstuvwxyz"]
let n = set1.length;
let m=set2.length;
document.write(countCompletePairs(set1, set2, n, m));
// This code is contributed by avanitrachhadiya2155
</script>
Time Complexity: O(n * m * k)
Auxiliary Space: O(1)
Method 2 (Optimized method using Bit Manipulation): In this method, we compress frequency array into an integer. We assign each bit of that integer with a character and we set it to 1 when the character is found. We perform this for all the strings in both the sets. Finally we just compare the two integers in the sets and if on combining all the bits are set, they form a complete string pair.
Implementation:
C++14
// C++ program to find count of complete pairs
#include <iostream>
using namespace std;
// Returns count of complete pairs from set[0..n-1]
// and set2[0..m-1]
int countCompletePairs(string set1[], string set2[],
int n, int m)
{
int result = 0;
// con_s1[i] is going to store an integer whose
// set bits represent presence/absence of characters
// in string set1[i].
// Similarly con_s2[i] is going to store an integer
// whose set bits represent presence/absence of
// characters in string set2[i]
int con_s1[n], con_s2[m];
// Process all strings in set1[]
for (int i = 0; i < n; i++) {
// initializing all bits to 0
con_s1[i] = 0;
for (int j = 0; j < set1[i].length(); j++) {
// Setting the ascii code of char s[i][j]
// to 1 in the compressed integer.
con_s1[i] = con_s1[i] | (1 << (set1[i][j] - 'a'));
}
}
// Process all strings in set2[]
for (int i = 0; i < m; i++) {
// initializing all bits to 0
con_s2[i] = 0;
for (int j = 0; j < set2[i].length(); j++) {
// setting the ascii code of char s[i][j]
// to 1 in the compressed integer.
con_s2[i] = con_s2[i] | (1 << (set2[i][j] - 'a'));
}
}
// assigning a variable whose all 26 (0..25)
// bits are set to 1
long long complete = (1 << 26) - 1;
// Now consider every pair of integer in con_s1[]
// and con_s2[] and check if the pair is complete.
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// if all bits are set, the strings are
// complete!
if ((con_s1[i] | con_s2[j]) == complete)
result++;
}
}
return result;
}
// Driver code
int main()
{
string set1[] = { "abcdefgh", "geeksforgeeks",
"lmnopqrst", "abc" };
string set2[] = { "ijklmnopqrstuvwxyz",
"abcdefghijklmnopqrstuvwxyz",
"defghijklmnopqrstuvwxyz" };
int n = sizeof(set1) / sizeof(set1[0]);
int m = sizeof(set2) / sizeof(set2[0]);
cout << countCompletePairs(set1, set2, n, m);
return 0;
}
Java
// Java program to find count of complete pairs
class GFG {
// Returns count of complete pairs from set[0..n-1]
// and set2[0..m-1]
static int countCompletePairs(String set1[], String set2[],
int n, int m)
{
int result = 0;
// con_s1[i] is going to store an integer whose
// set bits represent presence/absence of characters
// in string set1[i].
// Similarly con_s2[i] is going to store an integer
// whose set bits represent presence/absence of
// characters in string set2[i]
int[] con_s1 = new int[n];
int[] con_s2 = new int[m];
// Process all strings in set1[]
for (int i = 0; i < n; i++) {
// initializing all bits to 0
con_s1[i] = 0;
for (int j = 0; j < set1[i].length(); j++) {
// Setting the ascii code of char s[i][j]
// to 1 in the compressed integer.
con_s1[i] = con_s1[i] | (1 << (set1[i].charAt(j) - 'a'));
}
}
// Process all strings in set2[]
for (int i = 0; i < m; i++) {
// initializing all bits to 0
con_s2[i] = 0;
for (int j = 0; j < set2[i].length(); j++) {
// setting the ascii code of char s[i][j]
// to 1 in the compressed integer.
con_s2[i] = con_s2[i] | (1 << (set2[i].charAt(j) - 'a'));
}
}
// assigning a variable whose all 26 (0..25)
// bits are set to 1
long complete = (1 << 26) - 1;
// Now consider every pair of integer in con_s1[]
// and con_s2[] and check if the pair is complete.
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// if all bits are set, the strings are
// complete!
if ((con_s1[i] | con_s2[j]) == complete) {
result++;
}
}
}
return result;
}
// Driver code
public static void main(String args[])
{
String set1[] = { "abcdefgh", "geeksforgeeks",
"lmnopqrst", "abc" };
String set2[] = { "ijklmnopqrstuvwxyz",
"abcdefghijklmnopqrstuvwxyz",
"defghijklmnopqrstuvwxyz" };
int n = set1.length;
int m = set2.length;
System.out.println(countCompletePairs(set1, set2, n, m));
}
}
// This code contributed by Rajput-Ji
C#
// C# program to find count of complete pairs
using System;
class GFG {
// Returns count of complete pairs from set[0..n-1]
// and set2[0..m-1]
static int countCompletePairs(String[] set1, String[] set2,
int n, int m)
{
int result = 0;
// con_s1[i] is going to store an integer whose
// set bits represent presence/absence of characters
// in string set1[i].
// Similarly con_s2[i] is going to store an integer
// whose set bits represent presence/absence of
// characters in string set2[i]
int[] con_s1 = new int[n];
int[] con_s2 = new int[m];
// Process all strings in set1[]
for (int i = 0; i < n; i++) {
// initializing all bits to 0
con_s1[i] = 0;
for (int j = 0; j < set1[i].Length; j++) {
// Setting the ascii code of char s[i][j]
// to 1 in the compressed integer.
con_s1[i] = con_s1[i] | (1 << (set1[i][j] - 'a'));
}
}
// Process all strings in set2[]
for (int i = 0; i < m; i++) {
// initializing all bits to 0
con_s2[i] = 0;
for (int j = 0; j < set2[i].Length; j++) {
// setting the ascii code of char s[i][j]
// to 1 in the compressed integer.
con_s2[i] = con_s2[i] | (1 << (set2[i][j] - 'a'));
}
}
// assigning a variable whose all 26 (0..25)
// bits are set to 1
long complete = (1 << 26) - 1;
// Now consider every pair of integer in con_s1[]
// and con_s2[] and check if the pair is complete.
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// if all bits are set, the strings are
// complete!
if ((con_s1[i] | con_s2[j]) == complete) {
result++;
}
}
}
return result;
}
// Driver code
public static void Main(String[] args)
{
String[] set1 = { "abcdefgh", "geeksforgeeks",
"lmnopqrst", "abc" };
String[] set2 = { "ijklmnopqrstuvwxyz",
"abcdefghijklmnopqrstuvwxyz",
"defghijklmnopqrstuvwxyz" };
int n = set1.Length;
int m = set2.Length;
Console.WriteLine(countCompletePairs(set1, set2, n, m));
}
}
// This code has been contributed by 29AjayKumar
Python3
# Python3 program to find count of complete pairs
# Returns count of complete pairs from set[0..n-1]
# and set2[0..m-1]
def countCompletePairs(set1, set2, n, m):
result = 0
# con_s1[i] is going to store an integer whose
# set bits represent presence/absence of characters
# in set1[i].
# Similarly con_s2[i] is going to store an integer
# whose set bits represent presence/absence of
# characters in set2[i]
con_s1, con_s2 = [0] * n, [0] * m
# Process all strings in set1[]
for i in range(n):
# initializing all bits to 0
con_s1[i] = 0
for j in range(len(set1[i])):
# Setting the ascii code of char s[i][j]
# to 1 in the compressed integer.
con_s1[i] = con_s1[i] | (1 << (ord(set1[i][j]) - ord('a')))
# Process all strings in set2[]
for i in range(m):
# initializing all bits to 0
con_s2[i] = 0
for j in range(len(set2[i])):
# setting the ascii code of char s[i][j]
# to 1 in the compressed integer.
con_s2[i] = con_s2[i] | (1 << (ord(set2[i][j]) - ord('a')))
# assigning a variable whose all 26 (0..25)
# bits are set to 1
complete = (1 << 26) - 1
# Now consider every pair of integer in con_s1[]
# and con_s2[] and check if the pair is complete.
for i in range(n):
for j in range(m):
# if all bits are set, the strings are
# complete!
if ((con_s1[i] | con_s2[j]) == complete):
result += 1
return result
# Driver code
if __name__ == '__main__':
set1 = ["abcdefgh", "geeksforgeeks",
"lmnopqrst", "abc"]
set2 = ["ijklmnopqrstuvwxyz",
"abcdefghijklmnopqrstuvwxyz",
"defghijklmnopqrstuvwxyz"]
n = len(set1)
m = len(set2)
print(countCompletePairs(set1, set2, n, m))
# This code is contributed by mohit kumar 29
JavaScript
<script>
// Javascript program to find count of complete pairs
// Returns count of complete pairs from set[0..n-1]
// and set2[0..m-1]
function countCompletePairs(set1,set2,n,m)
{
let result = 0;
// con_s1[i] is going to store an integer whose
// set bits represent presence/absence of characters
// in string set1[i].
// Similarly con_s2[i] is going to store an integer
// whose set bits represent presence/absence of
// characters in string set2[i]
let con_s1 = new Array(n);
let con_s2 = new Array(m);
// Process all strings in set1[]
for (let i = 0; i < n; i++) {
// initializing all bits to 0
con_s1[i] = 0;
for (let j = 0; j < set1[i].length; j++) {
// Setting the ascii code of char s[i][j]
// to 1 in the compressed integer.
con_s1[i] = con_s1[i] |
(1 << (set1[i][j].charCodeAt(0) - 'a'.charCodeAt(0)));
}
}
// Process all strings in set2[]
for (let i = 0; i < m; i++) {
// initializing all bits to 0
con_s2[i] = 0;
for (let j = 0; j < set2[i].length; j++) {
// setting the ascii code of char s[i][j]
// to 1 in the compressed integer.
con_s2[i] = con_s2[i] |
(1 << (set2[i][j].charCodeAt(0) - 'a'.charCodeAt(0)));
}
}
// assigning a variable whose all 26 (0..25)
// bits are set to 1
let complete = (1 << 26) - 1;
// Now consider every pair of integer in con_s1[]
// and con_s2[] and check if the pair is complete.
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
// if all bits are set, the strings are
// complete!
if ((con_s1[i] | con_s2[j]) == complete) {
result++;
}
}
}
return result;
}
// Driver code
let set1=["abcdefgh", "geeksforgeeks",
"lmnopqrst", "abc"];
let set2=["ijklmnopqrstuvwxyz",
"abcdefghijklmnopqrstuvwxyz",
"defghijklmnopqrstuvwxyz" ]
let n = set1.length;
let m = set2.length;
document.write(countCompletePairs(set1, set2, n, m));
// This code is contributed by avanitrachhadiya2155
</script>
Time Complexity: O(n*m), where n is the size of the first set and m is the size of the second set.
Auxiliary Space: O(n)
This article is contributed by Rishabh Jain.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem