VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-array-contains-string-one-mismatch/

⇱ Find if an array contains a string with one mismatch - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

  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:


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


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)

Comment
Article Tags: