Open In App

Find if an array contains a string with one mismatch

Last Updated : 26 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:- 

  1. Check whether the string contained in arr is of the same length as the target string. 
  2. 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>


Output

0

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));


Output

True

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
Previous
Next
Share your thoughts in the comments

Similar Reads