Check if there is any common character in two given strings
Given two strings. The task is to check that is there any common character in between two strings.
Examples:
Input: s1 = "geeksforgeeks", s2 = "geeks"
Output: Yes
Input: s1 = "geeks", s2 = "for"
Output: No
Approach: Traverse the 1st string and map the characters of the string with its frequency, in this map characters act as a key and the frequency its value. Then traverse the second string and we will check if there is any character that is present in both the string then it is confirmed that there is a common sub-sequence.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool check(string s1, string s2)
{
map< char , int > map;
for ( int i = 0; i < s1.length(); i++)
map[s1[i]]++;
for ( int i = 0; i < s2.length(); i++)
if (map[s2[i]] > 0)
return true ;
return false ;
}
int main()
{
string s1 = "geeksforgeeks" , s2 = "geeks" ;
bool yes_or_no = check(s1, s2);
if (yes_or_no == true )
cout << "Yes" << endl;
else
cout << "No" << endl;
return 0;
}
|
Java
import java.util.*;
class GFG
{
static boolean check(String s1, String s2)
{
Map<Character, Integer> mp = new HashMap<>();
for ( int i = 0 ; i < s1.length(); i++)
{
mp.put(s1.charAt(i), mp.get(s1.charAt(i)) == null ? 1 : mp.get(s1.charAt(i)) + 1 );
}
for ( int i = 0 ; i < s2.length(); i++)
{
if (mp.get(s2.charAt(i)) > 0 )
{
return true ;
}
}
return false ;
}
public static void main(String[] args)
{
String s1 = "geeksforgeeks" , s2 = "geeks" ;
boolean yes_or_no = check(s1, s2);
if (yes_or_no == true )
{
System.out.println( "Yes" );
}
else
{
System.out.println( "No" );
}
}
}
|
Python3
def is_member( List , key):
for i in range ( 0 , len ( List )):
if key = = List [i]:
return True
return False
def overlap(List1 , List2):
for key in List1:
if is_member( List2, key ):
return True
return False
if __name__ = = '__main__' :
s1 = 'geeksforgeeks'
s2 = 'geeks'
List1 = list ( s1 )
List2 = list ( s2 )
yes_or_no = str (overlap( List1, List2 ))
if (yes_or_no):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static Boolean check(String s1, String s2)
{
Dictionary< char , int > mp = new Dictionary< char , int >();
for ( int i = 0; i < s1.Length; i++)
{
if (mp.ContainsKey(s1[i]))
{
var val = mp[s1[i]];
mp.Remove(s1[i]);
mp.Add(s1[i], val + 1);
}
else
{
mp.Add(s1[i], 1);
}
}
for ( int i = 0; i < s2.Length; i++)
{
if (mp[s2[i]] > 0)
{
return true ;
}
}
return false ;
}
public static void Main(String[] args)
{
String s1 = "geeksforgeeks" , s2 = "geeks" ;
Boolean yes_or_no = check(s1, s2);
if (yes_or_no == true )
{
Console.WriteLine( "Yes" );
}
else
{
Console.WriteLine( "No" );
}
}
}
|
Javascript
<script>
function check( s1, s2)
{
var map = new Map();
for ( var i = 0; i < s1.length; i++)
{
if (map.has(s1[i].charCodeAt(0)))
{
map[s1[i].charCodeAt(0)]++;
}
else
{
map[s1[i].charCodeAt(0)]=1;
}
}
for ( var i = 0; i < s2.length; i++)
if (map[s2[i].charCodeAt(0)] > 0)
return true ;
return false ;
}
var s1 = "geeksforgeeks" , s2 = "geeks" ;
var yes_or_no = check(s1, s2);
if (yes_or_no)
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(n) where n is the length of the string.
Auxiliary Space: O(n) where n is the length of the string.
Another Approach:
Convert str1 and str2 into sets of characters using the set() function.
Find the intersection of the two sets using the intersection() method, which returns a new set containing only the elements that are common to both sets.
Check if the resulting set common has at least one element using the len() function.
If the length of common is greater than 0, return True, indicating that there is at least one common character between str1 and str2.
If the length of common is 0, return False, indicating that there are no common characters between str1 and str2.
C++
#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
bool commonChars(string str1, string str2)
{
unordered_set< char > set1(str1.begin(), str1.end());
unordered_set< char > set2(str2.begin(), str2.end());
for ( char c : set1) {
if (set2.count(c)) {
return true ;
}
}
return false ;
}
int main() {
string string1 = "hello" ;
string string2 = "world" ;
if (commonChars(string1, string2)) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
return 0;
}
|
Java
import java.util.*;
public class Main {
public static boolean commonChars(String str1,
String str2)
{
Set<Character> set1 = new HashSet<>();
for ( char c : str1.toCharArray()) {
set1.add(c);
}
Set<Character> set2 = new HashSet<>();
for ( char c : str2.toCharArray()) {
set2.add(c);
}
for ( char c : set1) {
if (set2.contains(c)) {
return true ;
}
}
return false ;
}
public static void main(String[] args)
{
String string1 = "hello" ;
String string2 = "world" ;
if (commonChars(string1, string2)) {
System.out.println(
"Yes" );
}
else {
System.out.println(
"No" );
}
}
}
|
Python3
def commonChars(str1, str2):
set1 = set (str1)
set2 = set (str2)
common = set1.intersection(set2)
if len (common) > 0 :
return True
else :
return False
string1 = "hello"
string2 = "world"
if commonChars(string1, string2):
print ( "Yes" )
else :
print ( "No" )
|
Javascript
function commonChars(str1, str2) {
let set1 = new Set(str1);
let set2 = new Set(str2);
let common = new Set([...set1].filter(x => set2.has(x)));
if (common.size > 0) {
return true ;
} else {
return false ;
}
}
let string1 = "hello" ;
let string2 = "world" ;
if (commonChars(string1, string2)) {
console.log( "Yes" );
} else {
console.log( "No" );
}
|
C#
using System;
using System.Collections.Generic;
class Program {
static bool CommonChars( string str1, string str2)
{
HashSet< char > set1 = new HashSet< char >(str1);
HashSet< char > set2 = new HashSet< char >(str2);
foreach ( char c in set1)
{
if (set2.Contains(c)) {
return true ;
}
}
return false ;
}
static void Main( string [] args)
{
string string1 = "hello" ;
string string2 = "world" ;
if (CommonChars(string1, string2)) {
Console.WriteLine( "Yes" );
}
else {
Console.WriteLine( "No" );
}
}
}
|
Time complexity:
The time complexity of the set() function used to convert each input string into a set of characters is O(n), where n is the length of the input string.
The time complexity of the intersection() method used to find the common characters between the two sets is O(min(m, n)), where m and n are the sizes of the input sets.
The len() function used to check the size of the resulting set has a time complexity of O(1).
Overall, the time complexity of the function is O(n+m), where n and m are the lengths of the input strings.
Space complexity:
The space complexity of the function is O(n+m), where n and m are the lengths of the input strings. This is because the function creates two sets, each of which stores up to n and m characters, respectively.
Last Updated :
14 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...