Given two arrays of strings s[] and t[] of sizes n and m, respectively, find if they share at least one common string.
Examples:
Input: s[] = ["cake", "pastry", "fish", "candy"], t[] = ["burger", "ham", "fish", "cake", "sauce"]
Output: true
Explanation: The word "fish" is present in both arrays.Input: s[] = ["pizza", "chicken", "cake", "chilli", "candy"], t[] = ["choco", "coco"]
Output: false
Explanation: There is no common word in the two arrays.
Table of Content
[Naive Approach] Compare Every Pair of Strings - O(n * m * L) Time and O(1) Space
The idea is to compare every string in the first array with every string in the second array.
Working of Approach:
- Traverse each string in the first array.
- For every string, traverse all strings in the second array.
- Compare the current pair of strings.
- If both strings are equal, return true.
- If all pairs are checked without finding a common string, return false.
#include <bits/stdc++.h>
using namespace std;
bool commonString(vector<string> &s, vector<string> &t) {
for (string &str1 : s) {
for (string &str2 : t) {
if (str1 == str2) {
return true;
}
}
}
return false;
}
int main() {
vector<string> s = {"cake", "pastry", "fish", "candy"};
vector<string> t = {"burger", "ham", "fish", "cake", "sauce"};
cout << (commonString(s, t) ? "true" : "false");
return 0;
}
public class GFG {
static boolean commonString(String[] s, String[] t) {
for (String str1 : s) {
for (String str2 : t) {
if (str1.equals(str2)) {
return true;
}
}
}
return false;
}
public static void main(String[] args) {
String[] s = {"cake", "pastry", "fish", "candy"};
String[] t = {"burger", "ham", "fish", "cake", "sauce"};
System.out.println(commonString(s, t));
}
}
def commonString(s, t):
for str1 in s:
for str2 in t:
if str1 == str2:
return True
return False
if __name__ == "__main__":
s = ["cake", "pastry", "fish", "candy"]
t = ["burger", "ham", "fish", "cake", "sauce"]
print(str(commonString(s, t)).lower())
using System;
class GFG {
static bool commonString(string[] s, string[] t) {
foreach (string str1 in s) {
foreach (string str2 in t) {
if (str1 == str2) {
return true;
}
}
}
return false;
}
static void Main() {
string[] s = {"cake", "pastry", "fish", "candy"};
string[] t = {"burger", "ham", "fish", "cake", "sauce"};
Console.WriteLine(commonString(s, t).ToString().ToLower());
}
}
function commonString(s, t) {
for (const str1 of s) {
for (const str2 of t) {
if (str1 === str2) {
return true;
}
}
}
return false;
}
// Driver Code
const s = ["cake", "pastry", "fish", "candy"];
const t = ["burger", "ham", "fish", "cake", "sauce"];
console.log(commonString(s, t) ? "true" : "false");
Output
true
[Better Approach] Sort Both Arrays and Use Two Pointers - O(n log n + m log m) Time and O(1) Space
The idea is to sort both arrays so that equal strings appear at corresponding positions in lexicographical order. Then, use two pointers to traverse the arrays simultaneously.
Working of Approach:
- Sort both arrays in lexicographical order.
- Initialize two pointers, one for each array.
- Compare the strings at the current pointers.
- If both strings are equal, return true.
- If the string in the first array is lexicographically smaller, move its pointer forward.
- Otherwise, move the pointer of the second array forward.
- Repeat the process until one of the arrays is completely traversed.
- Return false if no common string is found.
#include <bits/stdc++.h>
using namespace std;
bool commonString(vector<string> &s, vector<string> &t) {
sort(s.begin(), s.end());
sort(t.begin(), t.end());
int i = 0, j = 0;
while (i < s.size() && j < t.size()) {
if (s[i] == t[j]) {
return true;
}
if (s[i] < t[j]) {
i++;
} else {
j++;
}
}
return false;
}
int main() {
vector<string> s = {"cake", "pastry", "fish", "candy"};
vector<string> t = {"burger", "ham", "fish", "cake", "sauce"};
cout << (commonString(s, t) ? "true" : "false");
return 0;
}
import java.util.Arrays;
public class GFG {
static boolean commonString(String[] s, String[] t) {
Arrays.sort(s);
Arrays.sort(t);
int i = 0, j = 0;
while (i < s.length && j < t.length) {
if (s[i].equals(t[j])) {
return true;
}
if (s[i].compareTo(t[j]) < 0) {
i++;
} else {
j++;
}
}
return false;
}
public static void main(String[] args) {
String[] s = {"cake", "pastry", "fish", "candy"};
String[] t = {"burger", "ham", "fish", "cake", "sauce"};
System.out.println(commonString(s, t));
}
}
def commonString(s, t):
s.sort()
t.sort()
i = j = 0
while i < len(s) and j < len(t):
if s[i] == t[j]:
return True
if s[i] < t[j]:
i += 1
else:
j += 1
return False
if __name__ == "__main__":
s = ["cake", "pastry", "fish", "candy"]
t = ["burger", "ham", "fish", "cake", "sauce"]
print(str(commonString(s, t)).lower())
using System;
class GFG {
static bool commonString(string[] s, string[] t) {
Array.Sort(s);
Array.Sort(t);
int i = 0, j = 0;
while (i < s.Length && j < t.Length) {
if (s[i] == t[j]) {
return true;
}
if (string.Compare(s[i], t[j]) < 0) {
i++;
} else {
j++;
}
}
return false;
}
static void Main() {
string[] s = {"cake", "pastry", "fish", "candy"};
string[] t = {"burger", "ham", "fish", "cake", "sauce"};
Console.WriteLine(commonString(s, t).ToString().ToLower());
}
}
function commonString(s, t) {
s.sort();
t.sort();
let i = 0, j = 0;
while (i < s.length && j < t.length) {
if (s[i] === t[j]) {
return true;
}
if (s[i] < t[j]) {
i++;
} else {
j++;
}
}
return false;
}
// Driver Code
const s = ["cake", "pastry", "fish", "candy"];
const t = ["burger", "ham", "fish", "cake", "sauce"];
console.log(commonString(s, t) ? "true" : "false");
Output
true
[Expected Approach] Use Hash Set - O(n + m) Time and O(n) Space
The idea is to store all the strings from one array in a hash set. Since a hash set provides constant-time lookup on average, each string from the second array can be checked efficiently.
Working of Approach:
- Create a hash set and insert all strings from the first array into it.
- Traverse each string in the second array.
- Check whether the current string exists in the hash set.
- If a match is found, return true.
- If all strings are checked without finding a match, return false.
#include <bits/stdc++.h>
using namespace std;
bool commonString(vector<string> &s, vector<string> &t) {
unordered_set<string> st(s.begin(), s.end());
for (string &str : t) {
if (st.count(str)) {
return true;
}
}
return false;
}
int main() {
vector<string> s = {"cake", "pastry", "fish", "candy"};
vector<string> t = {"burger", "ham", "fish", "cake", "sauce"};
cout << (commonString(s, t) ? "true" : "false");
return 0;
}
import java.util.HashSet;
public class GFG {
static boolean commonString(String[] s, String[] t) {
HashSet<String> set = new HashSet<>();
for (String str : s) {
set.add(str);
}
for (String str : t) {
if (set.contains(str)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
String[] s = {"cake", "pastry", "fish", "candy"};
String[] t = {"burger", "ham", "fish", "cake", "sauce"};
System.out.println(commonString(s, t) ? "true" : "false");
}
}
def commonString(s, t):
st = set(s)
for word in t:
if word in st:
return True
return False
if __name__ == "__main__":
s = ["cake", "pastry", "fish", "candy"]
t = ["burger", "ham", "fish", "cake", "sauce"]
print(str(commonString(s, t)).lower())
using System;
using System.Collections.Generic;
class GFG {
static bool commonString(string[] s, string[] t) {
HashSet<string> set = new HashSet<string>(s);
foreach (string str in t) {
if (set.Contains(str)) {
return true;
}
}
return false;
}
static void Main() {
string[] s = {"cake", "pastry", "fish", "candy"};
string[] t = {"burger", "ham", "fish", "cake", "sauce"};
Console.WriteLine(commonString(s, t).ToString().ToLower());
}
}
function commonString(s, t) {
const set = new Set(s);
for (const str of t) {
if (set.has(str)) {
return true;
}
}
return false;
}
// Driver Code
const s = ["cake", "pastry", "fish", "candy"];
const t = ["burger", "ham", "fish", "cake", "sauce"];
console.log(commonString(s, t) ? "true" : "false");
Output
true