VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-whether-strings-k-distance-apart-not/

⇱ Check whether Strings are k distance apart or not - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check whether Strings are k distance apart or not

Last Updated : 23 Jul, 2025

Given two strings, the task is to find if they are only less than or equal to k edit distance apart. It means that strings are only k edit distance apart when there are only k mismatches. 
Print Yes if there are less than or equal to k mismatches, Else No. 
Also, print yes if both strings are already the same.

Examples: 

Input : str1 = "geeksforgeeks" 
 str2 = "geeksforgeek" 
 k = 1
Output : Yes
Explanation: Only one character is mismatched 
 or to be removed i.e. s at last 

Input : str1 = "nishant" 
 str2 = "nisha" 
 k = 1
Output : No 
Explanation: 2 characters need to be removed
 i.e. n and t 

Input : str1 = "practice" 
 str2 = "prac" 
 k = 3
Output : No
Explanation: 4 characters are mismatched or to
 be removed i.e. t, i, c, e at last i.e. > k

Input : str1 = "Ping" str2 = "Paging" k = 2
Output : Yes 
Explanation: 2 characters need to be removed or 
 mismatched i.e. a and g in paging 

Algorithm: 

  1. Check if the difference in the length of both strings is greater than k. If so, return false. 
  2. Find the edit distance of two strings. If the edit distance is less than or equal to k, return true. Else return false. 

Implementation:


Output
Yes

Time Complexity : O(n*m), where n and m are length od string1 and string2 respectively.

Auxiliary Space : O(n*m), since we used dp[][] matrix of size n*m.

Comment
Article Tags:
Article Tags: