Open In App

Check whether Strings are k distance apart or not

Last Updated : 06 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

C++




// A Dynamic Programming based C++ program to
// find minimum number operations is less than
// or equal to k or not to convert str1 to str2
#include <bits/stdc++.h>
using namespace std;
 
// Utility function to find minimum of three numbers
int min(int x, int y, int z)
{
    return min(min(x, y), z);
}
 
int editDistDP(string str1, string str2, int m, int n)
{
    // Create a table to store results of subproblems
    int dp[m + 1][n + 1];
 
    // Fill d[][] in bottom up manner
    for (int i = 0; i <= m; i++) {
        for (int j = 0; j <= n; j++) {
            // If first string is empty, only option is to
            // insert all characters of second string
            if (i == 0)
                dp[i][j] = j; // Min. operations = j
 
            // If second string is empty, only option is to
            // remove all characters of second string
            else if (j == 0)
                dp[i][j] = i; // Min. operations = i
 
            // If last characters are same, ignore last char
            // and recur for remaining string
            else if (str1[i - 1] == str2[j - 1])
                dp[i][j] = dp[i - 1][j - 1];
 
            // If last character are different, consider all
            // possibilities and find minimum
            else
                dp[i][j] = 1 + min(dp[i][j - 1], // Insert
                                   dp[i - 1][j], // Remove
                                   dp[i - 1][j - 1]); // Replace
        }
    }
 
    return dp[m][n];
}
 
// Returns true if str1 and str2 are k edit distance apart,
// else false.
bool areKDistant(string str1, string str2, int k)
{
    int m = str1.length();
    int n = str2.length();
 
    if (abs(m - n) > k)
        return false;
 
    return (editDistDP(str1, str2, m, n) <= k);
}
 
// Driver program
int main()
{
    // your code goes here
    string str1 = "geek";
    string str2 = "gks";
    int k = 3;
 
    areKDistant(str1, str2, k) ? cout << "Yes" : cout << "No";
 
    return 0;
}


Java




// A Dynamic Programming based Java program to
// find minimum number operations is less than
// or equal to k or not to convert str1 to str2
class GFG {
 
    // Utility function to find minimum
    // of three numbers
    static int min(int x, int y, int z)
    {
        return Math.min(Math.min(x, y), z);
    }
 
    static int editDistDP(String str1, String str2,
                          int m, int n)
    {
        // Create a table to store
        // results of subproblems
        int dp[][] = new int[m + 1][n + 1];
 
        // Fill d[][] in bottom up manner
        for (int i = 0; i <= m; i++) {
            for (int j = 0; j <= n; j++) {
                // If first string is empty,
                // only option is to insert
                // all characters of second string
                if (i == 0)
                    dp[i][j] = j; // Min. operations = j
 
                // If second string is empty,
                // only option is to remove
                // all characters of second string
                else if (j == 0)
                    dp[i][j] = i; // Min. operations = i
 
                // If last characters are same,
                // ignore last char and recur
                // for remaining string
                else if (str1.charAt(i - 1) == str2.charAt(j - 1))
                    dp[i][j] = dp[i - 1][j - 1];
 
                // If last character are different,
                // consider all possibilities
                // and find minimum
                else
                    dp[i][j] = 1 + min(dp[i][j - 1], // Insert
                                       dp[i - 1][j], // Remove
                                       dp[i - 1][j - 1]); // Replace
            }
        }
 
        return dp[m][n];
    }
 
    // Returns true if str1 and str2 are
    // k edit distance apart, else false.
    static boolean areKDistant(String str1, String str2,
                               int k)
    {
        int m = str1.length();
        int n = str2.length();
 
        if (Math.abs(m - n) > k)
            return false;
 
        return (editDistDP(str1, str2, m, n) <= k);
    }
 
    // driver code
    public static void main(String[] args)
    {
        String str1 = "geek";
        String str2 = "gks";
        int k = 3;
 
        if (areKDistant(str1, str2, k))
            System.out.print("Yes");
        else
            System.out.print("No");
    }
}
 
// This code is contributed by Anant Agarwal.


Python3




# A Dynamic Programming based Python3 program to
# find minimum number operations is less than
# or equal to k or not to convert str1 to str2
 
# Utility function to find minimum
# of three numbers
def minn(x, y, z) :
 
    return min(min(x, y), z)
 
def editDistDP(str1, str2, m, n) :
 
    # Create a table to store results
    # of subproblems
    dp = [[0 for i in range(n + 1)]
             for j in range(m + 1)]
 
    # Fill d[][] in bottom up manner
    for i in range(m + 1):
        for j in range(n + 1):
             
            # If first is empty, only option is
            # to insert all characters of second
            if (i == 0) :
                dp[i][j] = j # Min. operations = j
 
            # If second is empty, only option is
            # to remove all characters of second
            else if (j == 0):
                dp[i][j] = i # Min. operations = i
 
            # If last characters are same,
            # ignore last char and recur
            # for remaining
            else if (str1[i - 1] == str2[j - 1]):
                dp[i][j] = dp[i - 1][j - 1]
 
            # If last character are different,
            # consider all possibilities and
            # find minimum
            else:
                dp[i][j] = 1 + minn(dp[i][j - 1], # Insert
                                    dp[i - 1][j], # Remove
                                    dp[i - 1][j - 1]) # Replace
         
    return dp[m][n]
 
# Returns true if str1 and str2 are
# k edit distance apart, else false.
def areKDistant(str1, str2, k):
 
    m = len(str1)
    n = len(str2)
 
    if (abs(m - n) > k) :
        return False
 
    return (editDistDP(str1, str2,
                       m, n) <= k)
 
# Driver Code
if __name__ == '__main__':
 
    str1 = "geek"
    str2 = "gks"
    k = 3
    if areKDistant(str1, str2, k):
        print("Yes"
    else:
        print("No")
 
# This code is contributed
# by SHUBHAMSINGH10


C#




// A Dynamic Programming based C#
// program to find minimum number
// operations is less than or equal
// to k or not to convert str1 to str2
using System;
 
class GFG
{
     
// Utility function to find minimum
// of three numbers
static int min(int x, int y, int z)
{
    return Math.Min(Math.Min(x, y), z);
}
 
static int editDistDP(string str1, string str2,
                      int m, int n)
{
     
    // Create a table to store
    // results of subproblems
    int [,]dp = new int[m + 1, n + 1];
 
    // Fill d[][] in bottom up manner
    for (int i = 0; i <= m; i++)
    {
        for (int j = 0; j <= n; j++)
        {
             
            // If first string is empty,
            // only option is to insert
            // all characters of second string
            if (i == 0)
             
                // Min. operations = j
                dp[i, j] = j;
 
            // If second string is empty,
            // only option is to remove
            // all characters of second string
            else if (j == 0)
             
                 // Min. operations = i
                dp[i, j] = i;
 
            // If last characters are same,
            // ignore last char and recur
            // for remaining string
            else if (str1[i - 1] == str2[j - 1])
                dp[i, j] = dp[i - 1,j - 1];
 
            // If last character are different,
            // consider all possibilities
            // and find minimum
            else
                dp[i, j] = 1 + min(dp[i, j - 1], // Insert
                                    dp[i - 1, j], // Remove
                                   dp[i - 1, j - 1]); // Replace
        }
    }
 
    return dp[m, n];
}
 
// Returns true if str1 and str2 are
// k edit distance apart, else false.
static bool areKDistant(string str1, string str2,
                        int k)
{
    int m = str1.Length;
    int n = str2.Length;
 
    if (Math.Abs(m - n) > k)
        return false;
 
    return (editDistDP(str1, str2, m, n) <= k);
}
 
// Driver Code
public static void Main ()
{
    string str1 = "geek";
    string str2 = "gks";
    int k = 3;
 
    if(areKDistant(str1, str2, k))
    Console.WriteLine("Yes");
    else
    Console.WriteLine("No");
}
}
 
// This code is contributed by vt_m.


PHP




<?php
// A Dynamic Programming based
// PHP program to find minimum
// number operations is less
// than or equal to k or not
// to convert str1 to str2
 
// Utility function to find
// minimum of three numbers
function minn($x, $y, $z)
{
    return min(minn($x, $y), $z);
}
 
function editDistDP($str1, $str2, $m, $n)
{
    // Create a table to store
    // results of subproblems
    $dp[$m + 1][$n + 1] = 0;
 
    // Fill d[][] in bottom up manner
    for ($i = 0; $i <= $m; $i++)
    {
        for ($j = 0; $j <= $n; $j++)
        {
            // If first string is empty,
            // only option is to insert
            // all characters of second string
            if ($i == 0)
             
                // Min. operations = j
                $dp[$i][$j] = $j;
 
            // If second string is empty,
            // only option is to remove all
            // characters of second string
            else if ($j == 0)
             
                // Min. operations = i
                $dp[$i][$j] = $i;
 
            // If last characters are same,
            // ignore last char and recur
            // for remaining string
            else if ($str1[$i - 1] == $str2[$j - 1])
                $dp[$i][$j] = $dp[$i - 1][$j - 1];
 
            // If last character are different,
            // consider all possibilities and
            // find minimum
            else
                                // Insert        
                $dp[$i][$j] = 1 + min($dp[$i][$j - 1],
                                // Remove
                                $dp[$i - 1][$j],
                                // Replace
                                $dp[$i - 1][$j - 1]);
        }
    }
 
    return $dp[$m][$n];
}
 
// Returns true if str1 and
// str2 are k edit distance
// apart, else false.
function areKDistant($str1, $str2, $k)
{
    $m = strlen($str1);
    $n = strlen($str2);
 
    if (abs($m - $n) > $k)
        return false;
 
    return (editDistDP($str1, $str2,
                       $m, $n) <= $k);
}
 
// Driver Code
$str1 = "geek";
$str2 = "gks";
$k = 3;
 
if(areKDistant($str1, $str2, $k))
echo"Yes" ;
else
echo "No";
 
// This code is contributed by nitin mittal.
?>


Javascript




<script>
    // A Dynamic Programming based Javascript program to
    // find minimum number operations is less than
    // or equal to k or not to convert str1 to str2
     
    // Utility function to find minimum
    // of three numbers
    function min(x, y, z)
    {
        return Math.min(Math.min(x, y), z);
    }
   
    function editDistDP(str1, str2, m, n)
    {
        // Create a table to store
        // results of subproblems
        let dp = new Array(m + 1);
   
        // Fill d[][] in bottom up manner
        for (let i = 0; i <= m; i++) {
            dp[i] = new Array(n + 1);
            for (let j = 0; j <= n; j++) {
                // If first string is empty,
                // only option is to insert
                // all characters of second string
                if (i == 0)
                    dp[i][j] = j; // Min. operations = j
   
                // If second string is empty,
                // only option is to remove
                // all characters of second string
                else if (j == 0)
                    dp[i][j] = i; // Min. operations = i
   
                // If last characters are same,
                // ignore last char and recur
                // for remaining string
                else if (str1[i - 1] == str2[j - 1])
                    dp[i][j] = dp[i - 1][j - 1];
   
                // If last character are different,
                // consider all possibilities
                // and find minimum
                else
                    dp[i][j] = 1 + min(dp[i][j - 1], // Insert
                                       dp[i - 1][j], // Remove
                                       dp[i - 1][j - 1]); // Replace
            }
        }
   
        return dp[m][n];
    }
   
    // Returns true if str1 and str2 are
    // k edit distance apart, else false.
    function areKDistant(str1, str2, k)
    {
        let m = str1.length;
        let n = str2.length;
   
        if (Math.abs(m - n) > k)
            return false;
   
        return (editDistDP(str1, str2, m, n) <= k);
    }
     
    let str1 = "geek";
    let str2 = "gks";
    let k = 3;
 
    if (areKDistant(str1, str2, k))
      document.write("Yes");
    else
      document.write("No");
     
</script>


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.

 



Next Article
Article Tags :
Practice Tags :

Similar Reads

Check if all the Nodes in a Binary Tree having common values are at least D distance apart
Given a Binary Tree and an integer D, the task is to check if the distance between all pairs of the same node values in the Tree is? D or not. If found to be true, then print Yes. Otherwise, print No. Examples: Input: D = 7 1 / \ 2 3 / \ / \ 4 3 4 4 Output: Yes Explanation: The repeated value of nodes are 3 and 4. The distance between the two nodes
11 min read
Minimum Sum of a pair at least K distance apart from an Array
Given an array of integers A[] of size N, the task is to find the minimum sum that can be obtained by any pair of array elements that are at least K indices apart from each other. Examples: Input: A[] = {1, 2, 3, 4, 5, 6}, K = 2 Output: 4 Explanation: The minimum sum that can be obtained is by adding 1 and 3 that are at a distance of 2.Input: A[] =
10 min read
Count pairs of leaf nodes in a Binary Tree which are at most K distance apart
Given a binary tree and an integer K, the task is to count the possible pairs of leaf nodes from the given binary tree such that the distance between them is at most K. Examples: Input: K = 3 1 / \ 2 3 / 4 Output: 1 Explanation: The leaf nodes of the tree are 3 and 4 And the shortest distance between them is 3. This is the only valid pair. Input: K
9 min read
Angle of intersection of two circles having their centers D distance apart
Given two positive integers R1 and R2 representing the radius of two intersecting circles having a distance D between their centers, the task is to find the cosine of the angle of intersection between the two circles. Examples: Input: R1 = 3, R2 = 4, D = 5Output: 0 Input: R1 = 7, R2 = 3, D = 6Output: 0.52381 Approach: The given problem can be solve
4 min read
Count of valid arrays of size P with elements in range [1, N] having duplicates at least M distance apart
Go to CDN's CopyGiven three integers N, M and P, the task is to find the total number of valid arrays that can be created of size P having each element in range [1, N], such that the duplicates appear at least M distance apart. Example: Input: N = 2, M = 0, P = 3Output: 6Explanation: All valid arrays are: {1, 2, 1}, {1, 1, 2}, {2, 1, 1}, {2, 2, 1},
9 min read
Count of Disjoint Groups by grouping points that are at most K distance apart
Given a 2D array arr[] and value K, where each list in arr[] represents a point on Cartesian coordinates, the task is to group the given points if the distance between them is less than or equal to K and find the total number of disjoint groups. Note: If points 'a' and 'b' are in the same group and 'a', 'd' are in the same group then 'b' and 'd' ar
11 min read
Maximize X such that Array can be sorted by swapping elements X distance apart
Given an input arr[] of length N, Which contains integers from 1 to N in unsorted order. You can apply only one type of operation on arr[] elements': Choose an index i and an integer X and swap Ai with an element that is X distance apart and both the indices are within the boundary of the array. Then the task is to find the maximum value of X by wh
10 min read
Maximum subsequence sum such that all elements are K distance apart
Given an array arr[] of N integers and another integer K. The task is to find the maximum sum of a subsequence such that the difference of the indices of all consecutive elements in the subsequence in the original array is exactly K. For example, if arr[i] is the first element of the subsequence then the next element has to be arr[i + k] then arr[i
10 min read
Check if every pair of 1 in the array is at least K length apart from each other
Given a binary array and an integer K, check if every pair of 1 in the array is at least K length apart from each other. Return true if the condition holds, otherwise return false. Examples: Input: arr = [1, 0, 0, 0, 1, 0, 0, 1, 0, 0], K = 2. Output: True Explanation: Every 1 in the array is at least K distance apart from each other. Input: arr= [1
5 min read
Check whether two strings can be made equal by reversing substring of equal length from both strings
Give two strings S1 and S2, the task is to check whether string S1 can be made equal to string S2 by reversing substring from both strings of equal length. Note: A substring can be reversed any number of times. Example: Input: S1 = "abbca", S2 = "acabb" Output: Yes Explanation: The string S1 and S2 can be made equal by: Reverse S1 in the range [2,
12 min read
Generate string with Hamming Distance as half of the hamming distance between strings A and B
Given two Binary string A and B of length N, the task is to find the Binary string whose Hamming Distance to strings A and B is half the Hamming Distance of A and B.Examples: Input: A = "1001010", B = "0101010" Output: 0001010 Explanation: The hamming distance of the string A and B is 2. The hamming distance of the output string to A is 1. The hamm
7 min read
Check whether two strings are equivalent or not according to given condition
Given two strings A and B of equal size. Two strings are equivalent either of the following conditions hold true: 1) They both are equal. Or, 2) If we divide the string A into two contiguous substrings of same size A1 and A2 and string B into two contiguous substrings of same size B1 and B2, then one of the following should be correct: A1 is recurs
12 min read
Count of 0s to be flipped to make any two adjacent 1s at least K 0s apart
Given a binary string s and a number K, the task is to find the maximum number of 0s that can be replaced by 1s such that two adjacent 1s are separated by at least K 0s in between them. Examples: Input: K = 2, s = "000000" Output: 2 Explanation:Change the 0s at position 0 and 3. Then the final string will be "100100" such that every 1 is separated
8 min read
Find the most frequent element K positions apart from X in given Array
Given an array nums[], and integer K and X, the task is to find the most frequent element K positions away from X in the given array. Examples: Input: nums = [1, 100, 200, 1, 100], K = 1, X = 1Output: 100Explanation: Elements 1 position apart from 1 is only 100.So the answer is 100. Input: nums = [2, 2, 2, 2, 3], K = 2, X = 2Output: X = 2 occurs in
6 min read
Check whether it is possible to join two points given on circle such that distance between them is k
Given two circles and a length, K. Find whether we can join two points (one on perimeter of each circle), so that distance between the points is K. (Coordinates of both points need not be an integer value). Examples: Input: Circle-1 Center (0, 0) Radius = 5 Circle-2 Center (8, 3) Radius = 2 K = 3 Output: Yes Maximum Distance: 15 Minimum Distance: 2
10 min read
Check if edit distance between two strings is one
An edit between two strings is one of the following changes. Add a characterDelete a characterChange a characterGiven two string s1 and s2, find if s1 can be converted to s2 with exactly one edit. Expected time complexity is O(m+n) where m and n are lengths of two strings. Examples: Input: s1 = "geeks", s2 = "geek" Output: yes Number of edits is 1
15 min read
Check whether given string can be generated after concatenating given strings
Given three strings str, A and B. The task is to check whether str = A + B or str = B + A where + denotes concatenation. Examples: Input: str = "GeeksforGeeks", A = "Geeksfo", B = "rGeeks" Output: Yes str = A + B = "Geeksfo" + "rGeeks" = "GeeksforGeeks"Input: str = "Delhicapitals", B = "Delmi", C = "capitals" Output: No Approach: If len(str) != len
11 min read
Check whether two strings can be made equal by increasing prefixes
In this problem we have to check. whether two strings can be made equal by increasing the ASCII value of characters of the prefix of first string. We can increase different prefixes multiple times. The strings consists of only lowercase alphabets and does not contain any special characters . Examples: Input : string 1="abcd", string 2="bcdd" Output
9 min read
Check whether two strings contain same characters in same order
Given two strings s1 and s2, the task is to find whether the two strings contain the same characters that occur in the same order. For example string "Geeks" and string "Geks" contain the same characters in same order. Examples: Input: s1 = "Geeks", s2 = "Geks" Output: Yes Input: s1 = "Arnab", s2 = "Andrew" Output: No Approach: We have two strings
9 min read
Check whether two strings can be made equal by copying their characters with the adjacent ones
Given two strings str1 and str2, the task is to check whether both of the string can be made equal by copying any character of the string with its adjacent character. Note that this operation can be performed any number of times.Examples: Input: str1 = "abc", str2 = "def" Output: No As all the characters in both the string are different. So, there
5 min read
Check whether an array of strings can correspond to a particular number X
Given an integer X and an array of strings str which represents numbers in any base ranging from [2, 36], the task is to check whether all the strings can be converted into X by assigning each string the desired base from 2 to 36, such that decimal base equivalent of the string is X. Examples: Input: str = {10000, 20, 16}, X = 16 Output: Yes Explan
9 min read
Check whether two strings are anagrams of each other using unordered_map in C++
Write a function to check whether two given strings are an Anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an Anagram of each other. Approach: Unordered Map can also be used to find if any two given strings are
3 min read
Javascript Program To Check Whether Two Strings Are Anagram Of Each Other
Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an anagram of each other. We strongly recommend that you click here and practice it, before moving on to t
7 min read
Count paths with distance equal to Manhattan distance
Given two points (x1, y1) and (x2, y2) in 2-D coordinate system. The task is to count all the paths whose distance is equal to the Manhattan distance between both the given points.Examples: Input: x1 = 2, y1 = 3, x2 = 4, y2 = 5 Output: 6Input: x1 = 2, y1 = 6, x2 = 4, y2 = 9 Output: 10 Approach: The Manhattan distance between the points (x1, y1) and
7 min read
Distance of chord from center when distance between center and another equal length chord is given
Given two equal length chords of a circle and Distance between the centre and one chord. The task is here to find the distance between the centre and the other chord. Examples: Input: 48 Output: 48 Input: 82 Output: 82 Below is the implementation of the above approach:Approach: Let AB & CD be the two equal chords of the circle having center at
3 min read
Minimal distance such that for every customer there is at least one vendor at given distance
Given N and M number of points on the straight line, denoting the positions of the customers and vendors respectively. Each vendor provides service to all customers, which are located at a distance that is no more than R from the vendor. The task is to find minimum R such that for each customer there is at least one vendor at the distance which is
7 min read
Maximise distance by rearranging all duplicates at same distance in given Array
Given an array arr[] of N integers. Arrange the array in a way such that the minimum distance among all pairs of same elements is maximum among all possible arrangements. The task is to find this maximum value. Examples: Input: arr[] = {1, 1, 2, 3}Output: 3Explanation: All possible arrangements are: {1, 1, 2, 3}, {1, 1, 3, 2}, {1, 2, 1, 3}, {1, 2,
6 min read
Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
A complete binary tree is a binary tree whose all levels except the last level are completely filled and all the leaves in the last level are all to the left side. More information about complete binary trees can be found here. Example:Below tree is a Complete Binary Tree (All nodes till the second last nodes are filled and all leaves are to the le
10 min read
Check whether a binary tree is a full binary tree or not | Iterative Approach
Given a binary tree containing n nodes. The problem is to check whether the given binary tree is a full binary tree or not. A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has only one child node. Examples: Input : 1 / \ 2 3 / \ 4 5 Outp
8 min read
Check whether a given string is Heterogram or not
Given a string S. The task is to check whether a the given string is Heterogram or not. A heterogram is a word, phrase, or sentence in which no letter of the alphabet occurs more than once. Examples: Input : S = "the big dwarf only jumps" Output : Yes Each alphabet in the string S is occurred only once. Input : S = "geeksforgeeks" Output : No Since
4 min read
  翻译: