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)
Similar Reads
Find missing elements from an Array with duplicates
Given an array arr[] of size N having integers in the range [1, N] with some of the elements missing. The task is to find the missing elements. Note: There can be duplicates in the array. Examples: Input: arr[] = {1, 3, 3, 3, 5}, N = 5Output: 2 4Explanation: The numbers missing from the list are 2 a
12 min read
Find a string which matches all the patterns in the given array
Given an array of strings arr[] which contains patterns of characters and "*" denoting any set of characters including the empty string. The task is to find a string that matches all the patterns in the array.Note: If there is no such possible pattern, print -1. Examples: Input: arr[] = {"pq*du*q",
10 min read
Find a String in given Array of Strings using Binary Search
Given a sorted array of Strings arr and a string x, The task is to find the index of x in the array using the Binary Search algorithm. If x is not present, return -1. Examples: Input: arr[] = {"contribute", "geeks", "ide", "practice"}, x = "ide"Output: 2Explanation: The String x is present at index
6 min read
How to check if an Array contains a value or not?
There are many ways for checking whether the array contains any specific value or not, one of them is: Examples: Input: arr[] = {10, 30, 15, 17, 39, 13}, key = 17Output: True Input: arr[] = {3, 2, 1, 7, 10, 13}, key = 20Output: False Approach: Using in-built functions: In C language there is no in-b
3 min read
Search in an array of strings where non-empty strings are sorted
Given an array of strings. The array has both empty and non-empty strings. All non-empty strings are in sorted order. Empty strings can be present anywhere between non-empty strings. Examples: Input : arr[] = {"for", "", "", "", "geeks", "ide", "", "practice", "" , "", "quiz", "", ""}; str = "quiz"
9 min read
Find a Fixed Point in an array with duplicates allowed
Given an array of n duplicates or distinct integers sorted in ascending order, write a function that returns a Fixed Point in the array, if there is any Fixed Point present in the array, else returns -1. Fixed Point in an array is an index i such that arr[i] is equal to i. Note that integers in the
8 min read
Find four missing numbers in an array containing elements from 1 to N
Given an array of unique integers where each integer of the given array lies in the range [1, N]. The size of array is (N-4). No Single element is repeated. Hence four numbers from 1 to N are missing in the array. Find the 4 missing numbers in sorted order. Examples: Input : arr[] = {2, 5, 6, 3, 9}O
10 min read
Count of strings that does not contain any character of a given string
Given an array arr containing N strings and a string str, the task is to find the number of strings that do not contain any character of string str. Examples: Input: arr[] = {"abcd", "hijk", "xyz", "ayt"}, str="apple"Output: 2Explanation: "hijk" and "xyz" are the strings that do not contain any char
8 min read
Find Last Palindrome String in the given Array
Given an array of strings arr[] of size N where each string consists only of lowercase English letter. The task is to return the last palindromic string in the array. Note: It guarantees that always one palindromic string is present. Examples: Input: arr[] = {"abc", "car", "ada", "racecar", "cool"}O
5 min read
Find all concatenations of words in Array
Given an array of strings arr[] (1 <= |arr[i]| <= 20) of size N (1 <= N <= 104), the task is to find all strings from the given array that are formed by the concatenation of strings in the same given array. Examples: Input: arr[]= { "geek", "geeks", "for", "geeksforgeeks", "g", "f", "g",
9 min read