Find if an array contains a string with one mismatch
Last Updated :
26 Apr, 2023
Given a string and array of strings, find whether the array contains a string with one character difference from the given string. Array may contain strings of different lengths.
Examples:
Input : str = "banana"
arr[] = {"bana", "apple", "banaba",
bonanzo", "banamf"}
Output :True
Explanation:-There is only a one character difference
between banana and banaba
Input : str = "banana"
arr[] = {"bana", "apple", "banabb", bonanzo",
"banamf"}
Output : False
We traverse through given string and check for every string in arr. Follow the two steps as given below for every string contained in arr:-
- Check whether the string contained in arr is of the same length as the target string.
- If yes, then check if there is only one character mismatch, if yes then return true else return false.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
bool check(vector<string> list, string s)
{
int n = ( int )list.size();
if (n == 0)
return false ;
for ( int i = 0; i < n; i++) {
if (list[i].size() != s.size())
continue ;
bool diff = false ;
for ( int j = 0; j < ( int )list[i].size(); j++) {
if (list[i][j] != s[j]) {
if (!diff)
diff = true ;
else {
diff = false ;
break ;
}
}
}
if (diff)
return true ;
}
return false ;
}
int main()
{
vector<string> s;
s.push_back( "bana" );
s.push_back( "apple" );
s.push_back( "banacb" );
s.push_back( "bonanza" );
s.push_back( "banamf" );
cout << check(s, "banana" );
return 0;
}
|
Java
import java.util.*;
class GFG
{
static boolean check(Vector<String> list, String s)
{
int n = ( int ) list.size();
if (n == 0 )
{
return false ;
}
for ( int i = 0 ; i < n; i++)
{
if (list.get(i).length() != s.length())
{
continue ;
}
boolean diff = false ;
for ( int j = 0 ; j < ( int ) list.get(i).length(); j++)
{
if (list.get(i).charAt(j) != s.charAt(j))
{
if (!diff)
{
diff = true ;
}
else
{
diff = false ;
break ;
}
}
}
if (diff) {
return true ;
}
}
return false ;
}
public static void main(String[] args)
{
Vector<String> s = new Vector<>();
s.add( "bana" );
s.add( "apple" );
s.add( "banacb" );
s.add( "bonanza" );
s.add( "banamf" );
System.out.println(check(s, "banana" ) == true ? 1 : 0 );
}
}
|
Python3
def check( list , s):
n = len ( list )
if (n = = 0 ):
return False
for i in range ( 0 , n, 1 ):
if ( len ( list [i]) ! = len (s)):
continue
diff = False
for j in range ( 0 , len ( list [i]), 1 ):
if ( list [i][j] ! = s[j]):
if (diff = = False ):
diff = True
else :
diff = False
break
if (diff):
return True
return False
if __name__ = = '__main__' :
s = []
s.append( "bana" )
s.append( "apple" )
s.append( "banacb" )
s.append( "bonanza" )
s.append( "banamf" )
print ( int (check(s, "banana" )))
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
static bool check(List<String> list, String s)
{
int n = ( int ) list.Count;
if (n == 0)
{
return false ;
}
for ( int i = 0; i < n; i++)
{
if (list[i].Length != s.Length)
{
continue ;
}
bool diff = false ;
for ( int j = 0; j < ( int ) list[i].Length; j++)
{
if (list[i][j] != s[j])
{
if (!diff)
{
diff = true ;
}
else
{
diff = false ;
break ;
}
}
}
if (diff) {
return true ;
}
}
return false ;
}
public static void Main(String[] args)
{
List<String> s = new List<String>();
s.Add( "bana" );
s.Add( "apple" );
s.Add( "banacb" );
s.Add( "bonanza" );
s.Add( "banamf" );
Console.WriteLine(check(s, "banana" ) == true ? 1 : 0);
}
}
|
Javascript
<script>
function check(list, s)
{
let n = list.length;
if (n == 0)
{
return false ;
}
for (let i = 0; i < n; i++)
{
if (list[i].length != s.length)
{
continue ;
}
let diff = false ;
for (let j = 0; j < list[i].length; j++)
{
if (list[i][j] != s[j])
{
if (!diff)
{
diff = true ;
}
else
{
diff = false ;
break ;
}
}
}
if (diff) {
return true ;
}
}
return false ;
}
let s = [];
s.push( "bana" );
s.push( "apple" );
s.push( "banacb" );
s.push( "bonanza" );
s.push( "banamf" );
document.write(check(s, "banana" ) == true ? 1 : 0);
</script>
|
Time complexity: O(n2)
Auxiliary space: O(1)
Approach#2: Using sorting
One more approach is to sort the array and then loop through each string in the array. For each string, compare it with the given string character by character and count the number of mismatches. If the count of mismatches is equal to 1, then return True.
Algorithm
1. Sort the array
2. Loop through each string in the array
3. Initialize a variable ‘count’ to 0
4. Loop through each character in the string
5. If the character in the given string at index ‘i’ is not equal to the character in the current string at index ‘i’, increment ‘count’ by 1
6. If ‘count’ becomes more than 1 or if the length of the string in the array is less than the length of the given string minus 1, continue to the next string
7. If the length of the string in the array is greater than the length of the given string plus 1, break out of the loop
8. If ‘count’ is equal to 1 and the length of the string in the array is either equal to the length of the given string or the length of the given string minus 1, return True
9. If the loop completes without finding a match, return False
C++
#include <bits/stdc++.h>
using namespace std;
bool has_one_mismatch(string str, vector<string> arr) {
sort(arr.begin(), arr.end());
for (string s : arr) {
int count = 0;
int i = 0;
while (i < s.length() && count <= 1) {
if (str[i] != s[i]) {
count += 1;
}
i += 1;
}
if (count > 1 || s.length() < str.length()-1) {
continue ;
}
if (s.length() > str.length()+1) {
break ;
}
if (count == 1 && (s.length() == str.length() || s.length() == str.length()-1)) {
return true ;
}
}
return false ;
}
int main() {
string str = "banana" ;
vector<string> arr = { "bana" , "apple" , "banaba" , "bonanzo" , "banamf" };
if (has_one_mismatch(str, arr)) cout<< "True" ;
else cout<< "False" ;
}
|
Java
import java.util.*;
public class Main {
public static boolean
has_one_mismatch(String str, ArrayList<String> arr)
{
Collections.sort(arr);
for (String s : arr) {
int count = 0 ;
int i = 0 ;
while (i < s.length() && count <= 1 ) {
if (str.charAt(i) != s.charAt(i)) {
count += 1 ;
}
i += 1 ;
}
if (count > 1
|| s.length() < str.length() - 1 ) {
continue ;
}
if (s.length() > str.length() + 1 ) {
break ;
}
if (count == 1
&& (s.length() == str.length()
|| s.length() == str.length() - 1 )) {
return true ;
}
}
return false ;
}
public static void main(String[] args)
{
String str = "banana" ;
ArrayList<String> arr = new ArrayList<String>(
Arrays.asList( "bana" , "apple" , "banaba" ,
"bonanzo" , "banamf" ));
if (has_one_mismatch(str, arr))
System.out.println( "True" );
else
System.out.println( "False" );
}
}
|
Python3
def has_one_mismatch( str , arr):
arr.sort()
for s in arr:
count = 0
i = 0
while i < len (s) and count < = 1 :
if str [i] ! = s[i]:
count + = 1
i + = 1
if count > 1 or len (s) < len ( str ) - 1 :
continue
if len (s) > len ( str ) + 1 :
break
if count = = 1 and ( len (s) = = len ( str ) or len (s) = = len ( str ) - 1 ):
return True
return False
str = "banana"
arr = [ "bana" , "apple" , "banaba" ,
"bonanzo" , "banamf" ]
print (has_one_mismatch( str , arr))
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static bool HasOneMismatch( string str, List< string > arr)
{
arr.Sort();
foreach ( string s in arr)
{
int count = 0;
int i = 0;
while (i < s.Length && count <= 1) {
if (str[i] != s[i]) {
count += 1;
}
i += 1;
}
if (count > 1 || s.Length < str.Length - 1) {
continue ;
}
if (s.Length > str.Length + 1) {
break ;
}
if (count == 1
&& (s.Length == str.Length
|| s.Length == str.Length - 1)) {
return true ;
}
}
return false ;
}
static void Main( string [] args)
{
string str = "banana" ;
List< string > arr
= new List< string >{ "bana" , "apple" , "banaba" ,
"bonanzo" , "banamf" };
if (HasOneMismatch(str, arr))
Console.WriteLine( "True" );
else
Console.WriteLine( "False" );
}
}
|
Javascript
function has_one_mismatch(str, arr) {
arr.sort();
for (let s of arr) {
let count = 0;
let i = 0;
while (i < s.length && count <= 1) {
if (str[i] != s[i]) {
count += 1;
}
i += 1;
}
if (count > 1 || s.length < str.length - 1) {
continue ;
}
if (s.length > str.length + 1) {
break ;
}
if (count == 1 && (s.length == str.length || s.length == str.length - 1)) {
return true ;
}
}
return false ;
}
let str = "banana" ;
let arr = [ "bana" , "apple" , "banaba" , "bonanzo" , "banamf" ];
console.log(has_one_mismatch(str, arr));
|
Time Complexity: O(nmlog(m)), where n is the length of the array and m is the length of the longest string in the array or the given string
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...