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++
// C++ program to find if given string is present
// with one mismatch.
#include <bits/stdc++.h>
using namespace std;
bool check(vector<string> list, string s)
{
int n = (int)list.size();
// If the array is empty
if (n == 0)
return false;
for (int i = 0; i < n; i++) {
// If sizes are same
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 first mismatch
if (!diff)
diff = true;
// Second mismatch
else {
diff = false;
break;
}
}
}
if (diff)
return true;
}
return false;
}
// Driver code
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.*;
// Java program to find if
// given string is present
// with one mismatch.
class GFG
{
static boolean check(Vector<String> list, String s)
{
int n = (int) list.size();
// If the array is empty
if (n == 0)
{
return false;
}
for (int i = 0; i < n; i++)
{
// If sizes are same
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 first mismatch
if (!diff)
{
diff = true;
}
// Second mismatch
else
{
diff = false;
break;
}
}
}
if (diff) {
return true;
}
}
return false;
}
// Driver code
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);
}
}
/* This code contributed by PrinciRaj1992 */
Python3
# Python 3 program to find if given
# string is present with one mismatch.
def check(list, s):
n = len(list)
# If the array is empty
if (n == 0):
return False
for i in range(0, n, 1):
# If sizes are same
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 first mismatch
if (diff == False):
diff = True
# Second mismatch
else:
diff = False
break
if (diff):
return True
return False
# Driver code
if __name__ == '__main__':
s = []
s.append("bana")
s.append("apple")
s.append("banacb")
s.append("bonanza")
s.append("banamf")
print(int(check(s, "banana")))
# This code is contributed by
# Sahil_shelangia
C#
// C# program to find if
// given string is present
// with one mismatch.
using System;
using System.Collections.Generic;
public class GFG
{
static bool check(List<String> list, String s)
{
int n = (int) list.Count;
// If the array is empty
if (n == 0)
{
return false;
}
for (int i = 0; i < n; i++)
{
// If sizes are same
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 first mismatch
if (!diff)
{
diff = true;
}
// Second mismatch
else
{
diff = false;
break;
}
}
}
if (diff) {
return true;
}
}
return false;
}
// Driver code
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);
}
}
// This code has been contributed by 29AjayKumar
JavaScript
<script>
// Javascript program to find if
// given string is present
// with one mismatch.
function check(list, s)
{
let n = list.length;
// If the array is empty
if (n == 0)
{
return false;
}
for (let i = 0; i < n; i++)
{
// If sizes are same
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 first mismatch
if (!diff)
{
diff = true;
}
// Second mismatch
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;
// Function to check if there is one mismatch between str and any string in arr
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;
}
// Driver code
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 {
// Function to check if there is one mismatch between
// str and any string in arr
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;
}
// driver code
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
{
// Function to check if there is one mismatch between
// str and any string in arr
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;
}
// driver code
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
// JavaScript code to check if a string has one mismatch
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 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 2.
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
Number of strings in two array satisfy the given conditions Given two arrays of string arr1[] and arr2[]. For each string in arr2[](say str2), the task is to count numbers string in arr1[](say str1) which satisfy the below conditions: The first characters of str1 and str2 must be equal.String str2 must contain each character of string str1.Examples: Input: a
14 min read
Find one extra character in a string Given two strings which are of lengths n and n+1. The second string contains all the characters of the first string, but there is one extra character. Your task is to find the extra character in the second string. Examples: Input : string strA = "abcd"; string strB = "cbdae"; Output : e string B con
15+ 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 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
Find missing element in a sorted array of consecutive numbers Given an array arr[] of n distinct integers. Elements are placed sequentially in ascending order with one element missing. The task is to find the missing element.Examples: Input: arr[] = {1, 2, 4, 5, 6, 7, 8, 9} Output: 3Input: arr[] = {-4, -3, -1, 0, 1, 2} Output: -2Input: arr[] = {1, 2, 3, 4} Out
7 min read
Palindrome pair in an array of words (or strings) Given an array of strings arr[] of size n, the task is to find if there exists two strings arr[i] and arr[j] such that arr[i]+arr[j] is a palindrome i.e the concatenation of string arr[i] and arr[j] results into a palindrome.Examples:Â Input: arr[] = ["geekf", "geeks", "or", "keeg", "abc", "bc"]Outpu
15+ min read