The Wayback Machine - https://web.archive.org/web/20240909000522/https://www.geeksforgeeks.org/edit-distance-dp-5/
Open In App

Edit Distance

Last Updated : 21 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given two strings s1 and s2 of lengths m and n respectively and below operations that can be performed on s1. Find the minimum number of edits (operations) to convert ‘s1‘ into ‘s2‘.  

  • Insert: Insert any character before or after any index of s1
  • Remove: Remove a character of s1
  • Replace: Replace a character at any index of s1 with some other character.

Note: All of the above operations are of equal cost. 

Examples: 

Input:   s1 = “geek”, s2 = “gesek”
Output:  1
Explanation: We can convert s1 into s2 by inserting a ‘s’ between two consecutive ‘e’ in s2.

Input:   s1 = “cat”, s2 = “cut”
Output:  1
Explanation: We can convert s1 into s2 by replacing ‘a’ with ‘u’.

Input:   s1 = “sunday”, s2 = “saturday”
Output:  3
Explanation: Last three and first characters are same.  We basically need to convert “un” to “atur”.  This can be done using below three operations. Replace ‘n’ with ‘r’, insert t, insert a

Illustration of Edit Distance:

Let’s suppose we have s1=”GEEXSFRGEEKKS” and s2=”GEEKSFORGEEKS”
Now to convert s1 into s2 we would require 3 minimum operations:
Operation 1: Replace ‘X‘ to ‘K‘
Operation 2: Insert ‘O‘ between ‘F‘ and ‘R‘
Operation 3: Remove second last character i.e. ‘K‘

Refer the below image for better understanding.

Edit-Distance-Illustration-(1)-copy

Using Recursion:

Subproblems in Edit Distance:

The idea is to process all characters one by one starting from either from left or right sides of both strings. 
Let us process from the right end of the strings, there are two possibilities for every pair of characters being traversed, either they match or they don’t match. If last characters of both string matches then we simply recursively calculate the answer for rest of part of the strings. When last characters do not match, we perform all three operations to match the last characters, i.e. insert, replace, and remove. We then recursively calculate the result for the remaining part of the string. Upon completion of these operations, we will select the minimum answer and add 1 to it.

Below is the recursive tree for this problem considering the case when the last characters never match.

When the last characters of strings matches. Make a recursive call editDist(m-1, n-1) to calculate the answer for remaining part of the strings.

When the last characters of strings don’t matches. Make three recursive calls as show below:

  • Insert s2[n-1] at last of s1 : editDist(m, n-1)
  • Replace s1[m-1] with s2[n-1] : editDist(m-1, n-1)
  • Remove s1[m-1] : editDist(m-1, n)

Recurrence Relations for Edit Distance:

  • Case 1: When the last character of both the strings are same. editDist(s1, s2, m, n) = editDist(s1, s2, m-1, n-1)
  • Case 2: When the last characters are different
    • editDist(s1, s2, m, n) = 1 + Minimum{ editDist(s1, s2 ,m,n-1), editDist(s1, s2 ,m-1, n), editDist(s1, s2 , m-1, n-1)}

Base Case for Edit Distance:

  • Case 1: When s1 becomes empty i.e. m=0
    • return n, as it require n insertions to convert an empty string to s2 of size n
  • Case 2: When s2 becomes empty i.e. n=0
    • return m, as it require m removals to convert s1 of size m to an empty string.

Below is the implementation of the above recursive solution.

C++
#include <bits/stdc++.h>
using namespace std;

// A Naive recursive C++ program to find minimum number
// of operations to convert s1 to s2
int editDistRec(string& s1, string& s2, int m, int n) {
  
    // If first string is empty, the only option is to
    // insert all characters of second string into first
    if (m == 0) return n;

    // If second string is empty, the only option is to
    // remove all characters of first string
    if (n == 0) return m;

    // If last characters of two strings are same, nothing
    // much to do. Get the count for
    // remaining strings.
    if (s1[m - 1] == s2[n - 1]) 
      return editDistRec(s1, s2, m - 1, n - 1);

    // If last characters are not same, consider all three
    // operations on last character of first string,
    // recursively compute minimum cost for all three
    // operations and take minimum of three values.
    return 1 + min({editDistRec(s1, s2, m, n - 1),   // Insert
                    editDistRec(s1, s2, m - 1, n),   // Remove
                    editDistRec(s1, s2, m - 1, n - 1)}); // Replace
}

// Wrapper function to initiate the recursive calculation
int editDist(string& s1, string& s2) {
    return editDistRec(s1, s2, s1.length(), s2.length());
}

// Driver code
int main() {
    // your code goes here
    string s1 = "GEEXSFRGEEKKS";
    string s2 = "GEEKSFORGEEKS";

    // Output the result of the edit distance calculation
    cout << editDist(s1, s2);

    return 0;
}
C
#include <stdio.h>
#include <string.h>

// Function to find minimum of three numbers
int min(int x, int y, int z) {
    return (x < y) ? (x < z ? x : z) : (y < z ? y : z);
}

// A Naive recursive C program to find minimum number
// of operations to convert s1 to s2
int editDistRec(char *s1, char *s2, int m, int n) {
    // If first string is empty, the only option is to
    // insert all characters of second string into first
    if (m == 0) return n;

    // If second string is empty, the only option is to
    // remove all characters of first string
    if (n == 0) return m;

    // If last characters of two strings are same, nothing
    // much to do. Get the count for
    // remaining strings.
    if (s1[m - 1] == s2[n - 1])
        return editDistRec(s1, s2, m - 1, n - 1);

    // If last characters are not same, consider all three
    // operations on last character of first string,
    // recursively compute minimum cost for all three
    // operations and take minimum of three values.
    return 1 + min(editDistRec(s1, s2, m, n - 1),    // Insert
                   editDistRec(s1, s2, m - 1, n),    // Remove
                   editDistRec(s1, s2, m - 1, n - 1) // Replace
                   );
}

int main() {
    char s1[] = "GEEXSFRGEEKKS";
    char s2[] = "GEEKSFORGEEKS";
    printf("%d\n", editDistRec(s1, s2, strlen(s1), strlen(s2)));
    return 0;
}
Java
public class GfG {
    // A Naive recursive Java program to find minimum number
    // of operations to convert s1 to s2
    public static int editDistRec(String s1, String s2, int m, int n) {
        // If first string is empty, the only option is to
        // insert all characters of second string into first
        if (m == 0) return n;

        // If second string is empty, the only option is to
        // remove all characters of first string
        if (n == 0) return m;

        // If last characters of two strings are same, nothing
        // much to do. Get the count for
        // remaining strings.
        if (s1.charAt(m - 1) == s2.charAt(n - 1))
            return editDistRec(s1, s2, m - 1, n - 1);

        // If last characters are not same, consider all three
        // operations on last character of first string,
        // recursively compute minimum cost for all three
        // operations and take minimum of three values.
        return 1 + Math.min(Math.min(editDistRec(s1, s2, m, n - 1),    // Insert
                                      editDistRec(s1, s2, m - 1, n)),  // Remove
                             editDistRec(s1, s2, m - 1, n - 1));     // Replace
    }

    // Wrapper function to initiate the recursive calculation
    public static int editDist(String s1, String s2) {
        return editDistRec(s1, s2, s1.length(), s2.length());
    }

    // Driver code
    public static void main(String[] args) {
        String s1 = "GEEXSFRGEEKKS";
        String s2 = "GEEKSFORGEEKS";
        System.out.println(editDist(s1, s2));
    }
}
Python
# A Naive recursive Python program to find minimum number
# of operations to convert s1 to s2
def editDistRec(s1, s2, m, n):
    # If first string is empty, the only option is to
    # insert all characters of second string into first
    if m == 0:
        return n

    # If second string is empty, the only option is to
    # remove all characters of first string
    if n == 0:
        return m

    # If last characters of two strings are same, nothing
    # much to do. Get the count for
    # remaining strings.
    if s1[m - 1] == s2[n - 1]:
        return editDistRec(s1, s2, m - 1, n - 1)

    # If last characters are not same, consider all three
    # operations on last character of first string,
    # recursively compute minimum cost for all three
    # operations and take minimum of three values.
    return 1 + min(editDistRec(s1, s2, m, n - 1),    # Insert
                   editDistRec(s1, s2, m - 1, n),    # Remove
                   editDistRec(s1, s2, m - 1, n - 1) # Replace
                   )

def editDist(s1, s2):
    return editDistRec(s1, s2, len(s1), len(s2))

# Driver code
s1 = "GEEXSFRGEEKKS"
s2 = "GEEKSFORGEEKS"
print(editDist(s1, s2))
C#
using System;

class GfG {
    // A Naive recursive C# program to find minimum number
    // of operations to convert s1 to s2
    static int EditDistRec(string s1, string s2, int m, int n) {
        // If first string is empty, the only option is to
        // insert all characters of second string into first
        if (m == 0) return n;

        // If second string is empty, the only option is to
        // remove all characters of first string
        if (n == 0) return m;

        // If last characters of two strings are same, nothing
        // much to do. Get the count for
        // remaining strings.
        if (s1[m - 1] == s2[n - 1])
            return EditDistRec(s1, s2, m - 1, n - 1);

        // If last characters are not same, consider all three
        // operations on last character of first string,
        // recursively compute minimum cost for all three
        // operations and take minimum of three values.
        return 1 + Math.Min(Math.Min(EditDistRec(s1, s2, m, n - 1),   // Insert
                                       EditDistRec(s1, s2, m - 1, n)),   // Remove
                              EditDistRec(s1, s2, m - 1, n - 1));  // Replace
    }

    static int EditDist(string s1, string s2) {
        return EditDistRec(s1, s2, s1.Length, s2.Length);
    }

    static void Main() {
        string s1 = "GEEXSFRGEEKKS";
        string s2 = "GEEKSFORGEEKS";
        Console.WriteLine(EditDist(s1, s2));
    }
}
JavaScript
// A Naive recursive JavaScript program to find minimum number
// of operations to convert s1 to s2
function editDistRec(s1, s2, m, n) {
    // If first string is empty, the only option is to
    // insert all characters of second string into first
    if (m === 0) return n;

    // If second string is empty, the only option is to
    // remove all characters of first string
    if (n === 0) return m;

    // If last characters of two strings are same, nothing
    // much to do. Get the count for
    // remaining strings.
    if (s1[m - 1] === s2[n - 1])
        return editDistRec(s1, s2, m - 1, n - 1);

    // If last characters are not same, consider all three
    // operations on last character of first string,
    // recursively compute minimum cost for all three
    // operations and take minimum of three values.
    return 1 + Math.min(editDistRec(s1, s2, m, n - 1),    // Insert
                        editDistRec(s1, s2, m - 1, n),    // Remove
                        editDistRec(s1, s2, m - 1, n - 1) // Replace
                        );
}

function editDist(s1, s2) {
    return editDistRec(s1, s2, s1.length, s2.length);
}

// Driver code
const s1 = "GEEXSFRGEEKKS";
const s2 = "GEEKSFORGEEKS";
console.log(editDist(s1, s2));

Output
3

Time Complexity: O(3^m), when length of “s1” <= length of “s2” and O(3^n), when length of “s2” < length of “s1”. Here m=length of “s1 and n=length of “s2”
Auxiliary Space: O(m), when length of “s1” <= length of “s2” and O(n), when length of “s2” < length of “s1”. Here m=length of “s1 and n=length of “s2”

Using Memoization:

In the above recursive approach, there are several overlapping subproblems:
editDist(m-1, n-1) is called Three times
editDist(m-1, n-2) is called Two times
editDist(m-2, n-1) is called Two times. And so on…

So, we can use Memoization to store the result of each subproblems to avoid recalculating the result again and again.

Below is the illustration of overlapping subproblems during the recursion.

Below is the implementation of Edit Distance Using Dynamic Programming (Memoization):

C++
#include <bits/stdc++.h>
using namespace std;

// Recursive function to find minimum edit distance between two strings
int minDisRec(string& s1, string& s2, int m, int n, 
                            vector<vector<int>>& memo) {
    if (m == 0) return n;

    if (n == 0) return m;

    if (memo[m][n] != -1) return memo[m][n];

    if (s1[m - 1] == s2[n - 1]) {
        memo[m][n] = minDisRec(s1, s2, m - 1, n - 1, memo);
    } else {
        memo[m][n] = 1 + min({
            minDisRec(s1, s2, m, n - 1, memo),    // Insert
            minDisRec(s1, s2, m - 1, n, memo),    // Remove
            minDisRec(s1, s2, m - 1, n - 1, memo) // Replace
        });
    }

    return memo[m][n]; // Return the computed minimum distance
}

// Function to initialize memoization table and start the recursive function
int minDis(string& s1, string& s2) {
    int m = s1.length(), n = s2.length();
    vector<vector<int>> memo(m + 1, vector<int>(n + 1, -1));
    return minDisRec(s1, s2, m, n, memo);
}

// Main function to execute the program
int main() {
    string s1 = "GEEXSFRGEEKKS"; // First string
    string s2 = "GEEKSFORGEEKS"; // Second string

    cout << minDis(s1, s2);
    return 0;
}
C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

// Recursive function to find minimum edit distance between two strings
int minDisRec(char *s1, char *s2, int m, int n, int **memo) {
    if (m == 0) return n;

    if (n == 0) return m;

    if (memo[m][n] != -1) return memo[m][n];

    if (s1[m - 1] == s2[n - 1]) {
        memo[m][n] = minDisRec(s1, s2, m - 1, n - 1, memo);
    } else {

        int insert = minDisRec(s1, s2, m, n - 1, memo);    // Insert
        int remove = minDisRec(s1, s2, m - 1, n, memo);    // Remove
        int replace = minDisRec(s1, s2, m - 1, n - 1, memo); // Replace
        memo[m][n] = 1 + (insert < remove ? (insert < replace ? insert : replace) : (remove < replace ? remove : replace));
    }

    return memo[m][n]; // Return the computed minimum distance
}

// Function to initialize memoization table and start the recursive function
int minDis(char *s1, char *s2) {
    int m = strlen(s1), n = strlen(s2);
    int **memo = (int **)malloc((m + 1) * sizeof(int *));
    for (int i = 0; i <= m; i++) {
        memo[i] = (int *)malloc((n + 1) * sizeof(int));
        for (int j = 0; j <= n; j++) {
            memo[i][j] = -1;
        }
    }
    return minDisRec(s1, s2, m, n, memo);
}

// Main function to execute the program
int main() {
    char s1[] = "GEEXSFRGEEKKS"; // First string
    char s2[] = "GEEKSFORGEEKS"; // Second string

    printf("%d\n", minDis(s1, s2));
    return 0;
}
Java
public class GfG {
    // Recursive function to find minimum edit distance between two strings
    private static int minDisRec(String s1, String s2, int m, int n, int[][] memo) {
      
        if (m == 0) return n;
      
        if (n == 0) return m;

        if (memo[m][n] != -1) return memo[m][n];

        if (s1.charAt(m - 1) == s2.charAt(n - 1)) {
            memo[m][n] = minDisRec(s1, s2, m - 1, n - 1, memo);
        } else {
          
            int insert = minDisRec(s1, s2, m, n - 1, memo);    // Insert
            int remove = minDisRec(s1, s2, m - 1, n, memo);    // Remove
            int replace = minDisRec(s1, s2, m - 1, n - 1, memo); // Replace
            memo[m][n] = 1 + Math.min(insert, Math.min(remove, replace));
        }

        return memo[m][n]; // Return the computed minimum distance
    }

    // Function to initialize memoization table and start the recursive function
    public static int minDis(String s1, String s2) {
        int m = s1.length(), n = s2.length();
        int[][] memo = new int[m + 1][n + 1];
        for (int i = 0; i <= m; i++) {
            for (int j = 0; j <= n; j++) {
                memo[i][j] = -1;
            }
        }
        return minDisRec(s1, s2, m, n, memo);
    }

    // Main function to execute the program
    public static void main(String[] args) {
        String s1 = "GEEXSFRGEEKKS"; // First string
        String s2 = "GEEKSFORGEEKS"; // Second string

        System.out.println(minDis(s1, s2));
    }
}
Python
# Recursive function to find minimum edit distance between two strings
def min_dis_rec(s1, s2, m, n, memo):
  
    if m == 0:
        return n

    if n == 0:
        return m

    if memo[m][n] is not None:
        return memo[m][n]

    if s1[m - 1] == s2[n - 1]:
        memo[m][n] = min_dis_rec(s1, s2, m - 1, n - 1, memo)
    else:
        insert = min_dis_rec(s1, s2, m, n - 1, memo)    # Insert
        remove = min_dis_rec(s1, s2, m - 1, n, memo)    # Remove
        replace = min_dis_rec(s1, s2, m - 1, n - 1, memo) # Replace
        memo[m][n] = 1 + min(insert, remove, replace)

    return memo[m][n] # Return the computed minimum distance

# Function to initialize memoization table and start the recursive function
def min_dis(s1, s2):
    m, n = len(s1), len(s2)
    memo = [[None] * (n + 1) for _ in range(m + 1)]
    return min_dis_rec(s1, s2, m, n, memo)

# Main function to execute the program
if __name__ == "__main__":
    s1 = "GEEXSFRGEEKKS" # First string
    s2 = "GEEKSFORGEEKS" # Second string

    print(min_dis(s1, s2))
C#
using System;

class GfG {
    // Recursive function to find minimum edit distance between two strings
    static int MinDisRec(string s1, string s2, int m, int n, int[,] memo) {

        if (m == 0) return n;
        if (n == 0) return m;

        if (memo[m, n] != -1) return memo[m, n];

        if (s1[m - 1] == s2[n - 1]) {
            memo[m, n] = MinDisRec(s1, s2, m - 1, n - 1, memo);
        } else {
            int insert = MinDisRec(s1, s2, m, n - 1, memo);    // Insert
            int remove = MinDisRec(s1, s2, m - 1, n, memo);    // Remove
            int replace = MinDisRec(s1, s2, m - 1, n - 1, memo); // Replace
            memo[m, n] = 1 + Math.Min(insert, Math.Min(remove, replace));
        }

        return memo[m, n]; // Return the computed minimum distance
    }

    // Function to initialize memoization table and start the recursive function
    static int MinDis(string s1, string s2) {
        int m = s1.Length, n = s2.Length;
        int[,] memo = new int[m + 1, n + 1];
        for (int i = 0; i <= m; i++) {
            for (int j = 0; j <= n; j++) {
                memo[i, j] = -1;
            }
        }
        return MinDisRec(s1, s2, m, n, memo);
    }

    // Main function to execute the program
    static void Main() {
        string s1 = "GEEXSFRGEEKKS"; // First string
        string s2 = "GEEKSFORGEEKS"; // Second string

        Console.WriteLine(MinDis(s1, s2));
    }
}
JavaScript
// Recursive function to find minimum edit distance between two strings
function minDisRec(s1, s2, m, n, memo) {
    if (m === 0) return n;

    if (n === 0) return m;

    if (memo[m][n] !== -1) return memo[m][n];

    if (s1[m - 1] === s2[n - 1]) {
        memo[m][n] = minDisRec(s1, s2, m - 1, n - 1, memo);
    } else {

        let insert = minDisRec(s1, s2, m, n - 1, memo);    // Insert
        let remove = minDisRec(s1, s2, m - 1, n, memo);    // Remove
        let replace = minDisRec(s1, s2, m - 1, n - 1, memo); // Replace
        memo[m][n] = 1 + Math.min(insert, remove, replace);
    }

    return memo[m][n]; // Return the computed minimum distance
}

// Function to initialize memoization table and start the recursive function
function minDis(s1, s2) {
    const m = s1.length, n = s2.length;
    const memo = Array.from({ length: m + 1 }, () => Array(n + 1).fill(-1));
    return minDisRec(s1, s2, m, n, memo);
}

// Main function to execute the program
const s1 = "GEEXSFRGEEKKS"; // First string
const s2 = "GEEKSFORGEEKS"; // Second string

console.log(minDis(s1, s2));

Output
3

Time Complexity: O(m x n) 
Auxiliary Space: O(m x n)

Using DP (Bottom-Up):

Use a table to store solutions of subproblems to avoiding recalculate the same subproblems multiple times. By doing this, if same subproblems repeated during, we retrieve the solutions from the table itself.

Below are the steps to convert the recursive approach to Bottom up approach:

1. Choosing Dimensions of Table: The state of smaller sub-problems depends on the input parameters m and n because at least one of them will decrease after each recursive call. So we need to construct a 2D table dp[][] to store the solution of the sub-problems.

2. Choosing Correct size of Table: The range of parameters goes from 0 to m and 0 to n. So we choose dimensions as (m + 1)*(n + 1)

3. Filling the table: It consist of two stages, table initialization and building the solution from the smaller subproblems:

  • Table initialization: Before building the solution, we need to initialize the table with the known values i.e. base case. Here m = 0 and n = 0 is the situation of the base case, so we initialize first-column dp[i][0] with i and first-row dp[0][j] with j.
  • Building the solution of larger problems from the smaller subproblems: We can easily define the iterative structure by using the recursive structure of the above recursive solution.
  • if (s1[i – 1] == s2[j – 1]) dp[i][j] = dp[i – 1][j – 1];
  • if (s1[i – 1] != s2[j – 1]) dp[i][j] = 1 + min(dp[i][j – 1], dp[i – 1][j], dp[i – 1][j – 1]);

4. Returning final solution: After filling the table iteratively, our final solution gets stored at the bottom right corner of the 2-D table i.e. we return dp[m][n] as an output.

Below is the implementation of the above algorithm:

C++
#include <bits/stdc++.h>
using namespace std;

int editDistDP(const string &s1, const string &s2) {
  
    int m = s1.length();
    int n = s2.length();

    // Create a table to store results of subproblems
    vector<vector<int>> dp(m + 1, vector<int>(n + 1));

    // Fill the known entries in dp[][]
    // If one string is empty, then answer 
    // is length of the other string
    for (int i = 0; i <= m; i++) 
        dp[i][0] = i;
    for (int j = 0; j <= n; j++) 
        dp[0][j] = j; 

    // Fill the rest of dp[][]
    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            if (s1[i - 1] == s2[j - 1])
                dp[i][j] = dp[i - 1][j - 1];
            else
                dp[i][j] = 1 + min({dp[i][j - 1],  
                                 dp[i - 1][j],   
                                 dp[i - 1][j - 1]});
        }
    }

    return dp[m][n];
}

// Driver code
int main() {
    string s1 = "GEEXSFRGEEKKS";
    string s2 = "GEEKSFORGEEKS";

    cout << editDistDP(s1, s2);

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int min(int x, int y, int z) {
    if (x < y)
        return (x < z) ? x : z;
    else
        return (y < z) ? y : z;
}

// Create a table to store results of subproblems
int editDistDP(const char *s1, const char *s2) {
    int m = strlen(s1);
    int n = strlen(s2);
    int dp[m + 1][n + 1];

    // Fill the known entries in dp[][]
    // If one string is empty, then answer 
    // is length of the other string
    for (int i = 0; i <= m; i++) 
        dp[i][0] = i;
    for (int j = 0; j <= n; j++) 
        dp[0][j] = j;

    // Fill the rest of dp[][]
    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            if (s1[i - 1] == s2[j - 1])
                dp[i][j] = dp[i - 1][j - 1];
            else
                dp[i][j] = 1 + min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]);
        }
    }

    return dp[m][n];
}

// Driver code
int main() {
    char s1[] = "GEEXSFRGEEKKS";
    char s2[] = "GEEKSFORGEEKS";

    printf("%d\n", editDistDP(s1, s2));

    return 0;
}
Java
public class GfG {
    // Create a table to store results of subproblems
    public static int editDistDP(String s1, String s2) {
        int m = s1.length();
        int n = s2.length();
        int[][] dp = new int[m + 1][n + 1];

        // Fill the known entries in dp[][]
        // If one string is empty, then answer 
        // is length of the other string
        for (int i = 0; i <= m; i++) 
            dp[i][0] = i;
        for (int j = 0; j <= n; j++) 
            dp[0][j] = j;

        // Fill the rest of dp[][]
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (s1.charAt(i - 1) == s2.charAt(j - 1))
                    dp[i][j] = dp[i - 1][j - 1];
                else
                    dp[i][j] = 1 + Math.min(dp[i][j - 1], Math.min(dp[i - 1][j], dp[i - 1][j - 1]));
            }
        }

        return dp[m][n];
    }

    // Driver code
    public static void main(String[] args) {
        String s1 = "GEEXSFRGEEKKS";
        String s2 = "GEEKSFORGEEKS";

        System.out.println(editDistDP(s1, s2));
    }
}
Python
def edit_dist_dp(s1, s2):
    m, n = len(s1), len(s2)

    # Create a table to store results of subproblems
    dp = [[0] * (n + 1) for _ in range(m + 1)]

    # Fill the known entries in dp[][]
    # If one string is empty, then answer 
    # is length of the other string
    for i in range(m + 1):
        dp[i][0] = i
    for j in range(n + 1):
        dp[0][j] = j

    # Fill the rest of dp[][]
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if s1[i - 1] == s2[j - 1]:
                dp[i][j] = dp[i - 1][j - 1]
            else:
                dp[i][j] = 1 + min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1])

    return dp[m][n]

# Driver code
s1 = "GEEXSFRGEEKKS"
s2 = "GEEKSFORGEEKS"
print(edit_dist_dp(s1, s2))
C#
using System;

class GfG {
    // Create a table to store results of subproblems
    public static int EditDistDP(string s1, string s2) {
        int m = s1.Length;
        int n = s2.Length;
        int[,] dp = new int[m + 1, n + 1];

        // Fill the known entries in dp[][]
        // If one string is empty, then answer 
        // is length of the other string
        for (int i = 0; i <= m; i++)
            dp[i, 0] = i;
        for (int j = 0; j <= n; j++)
            dp[0, j] = j;

        // Fill the rest of dp[][]
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (s1[i - 1] == s2[j - 1])
                    dp[i, j] = dp[i - 1, j - 1];
                else
                    dp[i, j] = 1 + Math.Min(dp[i, j - 1], Math.Min(dp[i - 1, j], dp[i - 1, j - 1]));
            }
        }

        return dp[m, n];
    }

    // Driver code
    static void Main() {
        string s1 = "GEEXSFRGEEKKS";
        string s2 = "GEEKSFORGEEKS";

        Console.WriteLine(EditDistDP(s1, s2));
    }
}
JavaScript
function editDistDP(s1, s2) {
    const m = s1.length;
    const n = s2.length;

    // Create a table to store results of subproblems
    const dp = Array.from(Array(m + 1), () => Array(n + 1));

    // Fill the known entries in dp[][]
    // If one string is empty, then answer 
    // is length of the other string
    for (let i = 0; i <= m; i++)
        dp[i][0] = i;
    for (let j = 0; j <= n; j++)
        dp[0][j] = j;

    // Fill the rest of dp[][]
    for (let i = 1; i <= m; i++) {
        for (let j = 1; j <= n; j++) {
            if (s1[i - 1] === s2[j - 1])
                dp[i][j] = dp[i - 1][j - 1];
            else
                dp[i][j] = 1 + Math.min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]);
        }
    }

    return dp[m][n];
}

// Driver code
const s1 = "GEEXSFRGEEKKS";
const s2 = "GEEKSFORGEEKS";

console.log(editDistDP(s1, s2));

Output
3

Time Complexity: O(m x n) 
Auxiliary Space: O(m x n)

Space Optimized DP (2*(n+1))

To fill a row in DP array we require only one row i.e. the upper row. For example, if we are filling the row where i=10 in DP array then we require only values of 9th row. So we create two one dimensional arrays, prev[] and curr[]. The array prev[] stores values of row i-1 and the array curr[] stores values of the current row i. This approach reduces the space complexity from O(m * n) to O(2*m).

Below is the implementation of the above approach:

C++
// A Space efficient Dynamic Programming
// based C++ program to find minimum
// number operations to convert s1 to s2
#include <bits/stdc++.h>
using namespace std;

// space optimization
int editDist(string& s1, string& s2)
{
    int m = s1.size();
    int n = s2.size();
 
    // prev stores results for (i-1) th row 
    // and curr for i-th row
    vector<int> prev(m + 1, 0), curr(n + 1, 0);

    // For 0-th row
    for (int j = 0; j <= n; j++)
        prev[j] = j;

    // Rest of the rows 
    for (int i = 1; i <= m; i++)
    {
        curr[0] = i;  // j = 0
        for (int j = 1; j <= n; j++)
        {
            if (s1[i - 1] == s2[j - 1])
                curr[j] = prev[j - 1];
            else            
                curr[j] = 1 + min({curr[j - 1], prev[j], prev[j - 1]});
        }
        prev = curr;
    }
    return prev[n];
}

int main()
{
    string s1 = "GEEXSFRGEEKKS", s2 = "GEEKSFORGEEKS";
    cout << editDist(s1, s2) << "\n";
    return 0;
}
C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

// A Space efficient Dynamic Programming
// based C program to find minimum
// number operations to convert s1 to s2

// space optimization
int editDist(char* s1, char* s2) {
    int m = strlen(s1);
    int n = strlen(s2);
    int *prev = (int*)malloc((n + 1) * sizeof(int));
    int *curr = (int*)malloc((n + 1) * sizeof(int));

    // For 0-th row
    for (int j = 0; j <= n; j++)
        prev[j] = j;

    // Rest of the rows 
    for (int i = 1; i <= m; i++) {
        curr[0] = i;  // j = 0
        for (int j = 1; j <= n; j++) {
            if (s1[i - 1] == s2[j - 1])
                curr[j] = prev[j - 1];
            else
                curr[j] = 1 + (curr[j - 1] < prev[j] ? (curr[j - 1] < prev[j - 1] ? curr[j - 1] : prev[j - 1]) : (prev[j] < prev[j - 1] ? prev[j] : prev[j - 1]));
        }
        int* temp = prev;
        prev = curr;
        curr = temp;
    }
    int result = prev[n];
    free(prev);
    free(curr);
    return result;
}

int main() {
    char s1[] = "GEEXSFRGEEKKS", s2[] = "GEEKSFORGEEKS";
    printf("%d\n", editDist(s1, s2));
    return 0;
}
Java
public class GfG {

    // A Space efficient Dynamic Programming
    // based Java program to find minimum
    // number operations to convert s1 to s2

    // space optimization
    public static int editDist(String s1, String s2) {
        int m = s1.length();
        int n = s2.length();
        int[] prev = new int[n + 1];
        int[] curr = new int[n + 1];

        // For 0-th row
        for (int j = 0; j <= n; j++)
            prev[j] = j;

        // Rest of the rows 
        for (int i = 1; i <= m; i++) {
            curr[0] = i;  // j = 0
            for (int j = 1; j <= n; j++) {
                if (s1.charAt(i - 1) == s2.charAt(j - 1))
                    curr[j] = prev[j - 1];
                else
                    curr[j] = 1 + Math.min(curr[j - 1], Math.min(prev[j], prev[j - 1]));
            }
            int[] temp = prev;
            prev = curr;
            curr = temp;
        }
        return prev[n];
    }

    public static void main(String[] args) {
        String s1 = "GEEXSFRGEEKKS", s2 = "GEEKSFORGEEKS";
        System.out.println(editDist(s1, s2));
    }
}
Python
# A Space efficient Dynamic Programming
# based Python program to find minimum
# number operations to convert s1 to s2

# space optimization
def edit_dist(s1, s2):
    m, n = len(s1), len(s2)
    prev = list(range(n + 1))

    # Rest of the rows
    for i in range(1, m + 1):
        curr = [i]  # j = 0
        for j in range(1, n + 1):
            if s1[i - 1] == s2[j - 1]:
                curr.append(prev[j - 1])
            else:
                curr.append(1 + min(curr[-1], prev[j], prev[j - 1]))
        prev = curr
    return prev[n]

# Driver code
s1 = "GEEXSFRGEEKKS"
s2 = "GEEKSFORGEEKS"
print(edit_dist(s1, s2))
C#
using System;

class GfG {
    // A Space efficient Dynamic Programming
    // based C# program to find minimum
    // number operations to convert s1 to s2

    // space optimization
    public static int EditDist(string s1, string s2) {
        int m = s1.Length;
        int n = s2.Length;
        int[] prev = new int[n + 1];
        int[] curr = new int[n + 1];

        // For 0-th row
        for (int j = 0; j <= n; j++)
            prev[j] = j;

        // Rest of the rows 
        for (int i = 1; i <= m; i++) {
            curr[0] = i;  // j = 0
            for (int j = 1; j <= n; j++) {
                if (s1[i - 1] == s2[j - 1])
                    curr[j] = prev[j - 1];
                else
                    curr[j] = 1 + Math.Min(curr[j - 1], Math.Min(prev[j], prev[j - 1]));
            }
            var temp = prev;
            prev = curr;
            curr = temp;
        }
        return prev[n];
    }

    static void Main() {
        string s1 = "GEEXSFRGEEKKS";
        string s2 = "GEEKSFORGEEKS";
        Console.WriteLine(EditDist(s1, s2));
    }
}
JavaScript
// A Space efficient Dynamic Programming
// based JavaScript program to find minimum
// number operations to convert s1 to s2

// space optimization
function editDist(s1, s2) {
    let m = s1.length;
    let n = s2.length;
    let prev = Array.from({length: n + 1}, (_, i) => i);

    // Rest of the rows
    for (let i = 1; i <= m; i++) {
        let curr = [i];  // j = 0
        for (let j = 1; j <= n; j++) {
            if (s1[i - 1] === s2[j - 1]) {
                curr[j] = prev[j - 1];
            } else {
                curr[j] = 1 + Math.min(curr[j - 1], prev[j], prev[j - 1]);
            }
        }
        prev = curr;
    }
    return prev[n];
}

// Driver code
const s1 = "GEEXSFRGEEKKS";
const s2 = "GEEKSFORGEEKS";
console.log(editDist(s1, s2));

Output
3

Time Complexity: O(m x n) 
Auxiliary Space: O(n), Length of the s2

Further Space Optimization ((n+1)):

The answer is Yes and it requires a simple observation as mentioned below:
In the previous approach The curr[] array is updated using 3 values only :

Value 1: curr[j] = prev[j-1] when s1[i-1] is equal to s2[j-1]
Value 2: curr[j] = prev[j] when s1[i-1] is not equal to s2[j-1]
Value 3: curr[j] = curr[j-1] when s1[i-1] is not equal to s2[j-1]

By keeping the track of these three values we can achiever our task using only a single 1-D array

Below is the code implementation of the approach:

C++
// A Space efficient Dynamic Programming
// based C++ program to find minimum
// number operations to convert s1 to s2
#include <bits/stdc++.h>
using namespace std;

int editDist(string& s1, string& s2)
{
    int m = s1.size();
    int n = s2.size();
    int prev; // Stores dp[i-1][j-1]
    vector<int> curr(n + 1, 0); // Stores dp[i][j-1]
                                // and dp[i][j]

    for (int j = 0; j <= n; j++)
        curr[j] = j;
  
    for (int i = 1; i <= m; i++)
    {
        prev = curr[0]; 
        curr[0] = i;
        for (int j = 1; j <= n; j++)
        {
            int temp = curr[j];
            if (s1[i - 1] == s2[j - 1])
                curr[j] = prev;
            else
                curr[j] = 1 + min({curr[j - 1], prev, curr[j]});
            prev = temp;
        }
    }
    return curr[n];
}

int main()
{
    string s1 = "GEEXSFRGEEKKS", s2 = "GEEKSFORGEEKS";
    cout << editDist(s1, s2) << "\n";
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// A Space efficient Dynamic Programming
// based C program to find minimum
// number operations to convert s1 to s2

int min(int x, int y, int z) {
    return (x < y) ? (x < z ? x : z) : (y < z ? y : z);
}

int editDist(char* s1, char* s2) {
    int m = strlen(s1);
    int n = strlen(s2);
    int prev, temp;
    int* curr = (int*) malloc((n + 1) * sizeof(int));

    // Stores dp[i][j-1]
    // and dp[i][j]
    for (int j = 0; j <= n; j++)
        curr[j] = j;

    for (int i = 1; i <= m; i++) {
        prev = curr[0];
        curr[0] = i;
        for (int j = 1; j <= n; j++) {
            temp = curr[j];
            if (s1[i - 1] == s2[j - 1])
                curr[j] = prev;
            else
                curr[j] = 1 + min(curr[j - 1], prev, curr[j]);
            prev = temp;
        }
    }
    int result = curr[n];
    free(curr);
    return result;
}

int main() {
    char s1[] = "GEEXSFRGEEKKS";
    char s2[] = "GEEKSFORGEEKS";
    printf("%d\n", editDist(s1, s2));
    return 0;
}
Java
public class GfG {

    // A Space efficient Dynamic Programming
    // based Java program to find minimum
    // number operations to convert s1 to s2

    public static int editDist(String s1, String s2) {
        int m = s1.length();
        int n = s2.length();
        int prev; // Stores dp[i-1][j-1]
        int[] curr = new int[n + 1]; // Stores dp[i][j-1] and dp[i][j]

        for (int j = 0; j <= n; j++)
            curr[j] = j;

        for (int i = 1; i <= m; i++) {
            prev = curr[0];
            curr[0] = i;
            for (int j = 1; j <= n; j++) {
                int temp = curr[j];
                if (s1.charAt(i - 1) == s2.charAt(j - 1))
                    curr[j] = prev;
                else
                    curr[j] = 1 + Math.min(curr[j - 1], Math.min(prev, curr[j]));
                prev = temp;
            }
        }
        return curr[n];
    }

    public static void main(String[] args) {
        String s1 = "GEEXSFRGEEKKS", s2 = "GEEKSFORGEEKS";
        System.out.println(editDist(s1, s2));
    }
}
Python
# A Space efficient Dynamic Programming
# based Python program to find minimum
# number operations to convert s1 to s2

def edit_dist(s1, s2):
    m, n = len(s1), len(s2)
    prev = 0  # Stores dp[i-1][j-1]
    curr = list(range(n + 1))  # Stores dp[i][j-1] and dp[i][j]

    for i in range(1, m + 1):
        prev = curr[0]
        curr[0] = i
        for j in range(1, n + 1):
            temp = curr[j]
            if s1[i - 1] == s2[j - 1]:
                curr[j] = prev
            else:
                curr[j] = 1 + min(curr[j - 1], prev, curr[j])
            prev = temp
    return curr[n]

# Driver code
s1 = "GEEXSFRGEEKKS"
s2 = "GEEKSFORGEEKS"
print(edit_dist(s1, s2))
C#
using System;

class GfG {
    // A Space efficient Dynamic Programming
    // based C# program to find minimum
    // number operations to convert s1 to s2

    static int EditDist(string s1, string s2) {
        int m = s1.Length;
        int n = s2.Length;
        int prev;  // Stores dp[i-1][j-1]
        int[] curr = new int[n + 1];  // Stores dp[i][j-1] and dp[i][j]

        for (int j = 0; j <= n; j++)
            curr[j] = j;

        for (int i = 1; i <= m; i++) {
            prev = curr[0];
            curr[0] = i;
            for (int j = 1; j <= n; j++) {
                int temp = curr[j];
                if (s1[i - 1] == s2[j - 1])
                    curr[j] = prev;
                else
                    curr[j] = 1 + Math.Min(curr[j - 1], Math.Min(prev, curr[j]));
                prev = temp;
            }
        }
        return curr[n];
    }

    static void Main() {
        string s1 = "GEEXSFRGEEKKS";
        string s2 = "GEEKSFORGEEKS";
        Console.WriteLine(EditDist(s1, s2));
    }
}
JavaScript
// A Space efficient Dynamic Programming
// based JavaScript program to find minimum
// number operations to convert s1 to s2

function editDist(s1, s2) {
    let m = s1.length;
    let n = s2.length;
    let prev;  // Stores dp[i-1][j-1]
    let curr = Array.from({length: n + 1}, (_, i) => i);  // Stores dp[i][j-1] and dp[i][j]

    for (let i = 1; i <= m; i++) {
        prev = curr[0];
        curr[0] = i;
        for (let j = 1; j <= n; j++) {
            let temp = curr[j];
            if (s1[i - 1] === s2[j - 1])
                curr[j] = prev;
            else
                curr[j] = 1 + Math.min(curr[j - 1], prev, curr[j]);
            prev = temp;
        }
    }
    return curr[n];
}

// Driver code
const s1 = "GEEXSFRGEEKKS";
const s2 = "GEEKSFORGEEKS";
console.log(editDist(s1, s2));

Output
3

Time Complexity: O(m*n)
Auxiliary Space: O(n)

Real-World Applications of Edit Distance:

  • Spell Checking and Auto-Correction
  • DNA Sequence Alignment
  • Plagiarism Detection
  • Natural Language Processing
  • Version Control Systems
  • String Matching

Edit Distance and Longest Common Subsequence:

If we do not consider the replace operation, then edit distance problem is same as the Longest Common Subsequence (LCS) problem. With only insert and delete operations allowed, the edit distance between two strings is ( M + N – 2* LCS)

Interview Question based on Edit Distance:

You may refer edit distance based articles to know interview based questions based on edit distance.



Similar Reads

Edit Distance | DP using Memoization
Given two strings str1 and str2 and below operations that can be performed on str1. Find the minimum number of edits (operations) required to convert 'str1' into 'str2'. InsertRemoveReplace All of the above operations are of equal cost. Examples: Input: str1 = "geek", str2 = "gesek" Output: 1 We can convert str1 into str2 by inserting a 's'. Input:
15+ 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
CSES Solutions - Edit Distance
The edit distance between two strings S1 and S2 is the minimum number of operations required to transform one string into the other. The allowed operations are: Add one character to the string.Remove one character from the string.Replace one character in the string.Your task is to calculate the edit distance between two strings. Examples: Input: S1
8 min read
Edit distance and LCS (Longest Common Subsequence)
In standard Edit Distance where we are allowed 3 operations, insert, delete, and replace. Consider a variation of edit distance where we are allowed only two operations insert and delete, find edit distance in this variation. Examples: Input : str1 = "cat", st2 = "cut"Output : 2We are allowed to insert and delete. We delete 'a'from "cat" and insert
6 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 &amp; CD be the two equal chords of the circle having center at
3 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
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
Rearrange a string so that all same characters become d distance away
Given a string and a positive integer d. Some characters may be repeated in the given string. Rearrange characters of the given string such that the same characters become d distance away from each other. Note that there can be many possible rearrangements, the output should be one of the possible rearrangements. If no such arrangement is possible,
14 min read
Check if a path exists in a tree with K vertices present or are at most at a distance D
Given a tree with N vertices numbered [0, n - 1], K vertices, and a distance D, the task is to find whether there is a path from the root to some vertex such that each of the K vertices belongs to the path or are at most at a distance D from the path. Examples: Input: 0 / \ / \ 1 2 / \ / \ / \ / \ 3 4 5 8 / \ / \ 6 7 / / 9 K = {6, 7, 8, 5}, D = 1 O
12 min read
Pair with given sum and maximum shortest distance from end
Given an array of N integers and an integer K, pick two distinct elements whose sum is K and find the maximum shortest distance of the picked elements from the endpoints. Examples: Input : a[] = {2, 4, 3, 2, 1} k = 5. Output : 2 Explanation: Select the pair(4, 1). Shortest distance of 4 from ends = 2 Shortest distance of 1 from ends = 1 Hence, answ
8 min read
Find a rotation with maximum hamming distance
Given an array of N elements, create a new array which is a rotation of the given array, and hamming distance between both the arrays is maximum. The task is to print the maximized hamming distance between given and new arrays. Hamming distance between two arrays or strings of equal length is the number of positions at which the corresponding chara
15+ min read
Find the distance covered to collect items at equal distances
A race is going on in which several stones are placed on a road. A bucket is placed at the starting point of the race, which is 5 units away from the first stone. The other stones are 3 units apart from each other and lie straight in a line one after another. I.e., the distance between 1st and 2nd stone is 3 units, between 3rd and 4th stone, it is
5 min read
Distance between two closest minimum
Given an array of n integers. Find the minimum distance between any two occurrences of the minimum integer in the array. Examples: Input : arr[] = {5, 1, 2, 3, 4, 1, 2, 1} Output : 2 Explanation: The minimum element 1 occurs at indexes: 1, 5 and 7. So the minimum distance is 7-5 = 2. Input : arr[] = {1, 2, 1} Output : 2 Brute Force Approach: The si
10 min read
Reduce Hamming distance by swapping two characters
Given two strings S and T. Find the positions of two letters to be swapped in S so that the hamming distance between strings S and T is as small as possible. Hamming Distance: Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters Examples: Input : S =
10 min read
Distance between two points travelled by a boat
Write a program to determine the distance(D) between two points traveled by a boat, given the speed of boat in still water(B), the speed of the stream(S), the time taken to row a place and come back i.e T. Examples: Input : B = 5, S = 1, T = 1 Output : D = 2.4 Input : B = 5, S = 2, T = 1 Output : D = 2.1 Formula for distance is D = T*(B^2 - S^2)/ (
4 min read
Calculate speed, distance and time
When an object moves in a straight line at a steady speed, we can calculate its speed if we know how far it travels and how long it takes. This equation shows the relationship between speed, distance travelled and time taken: Speed is distance divided by the time taken. For example, a car travels 30 kilometres in 2 hours. Its speed is 30 ÷ 2 = 15km
6 min read
Minimum distance between two occurrences of maximum
You are given an array of n-elements with a basic condition that occurrence of greatest element is more than once. You have to find the minimum distance between maximums. (n&gt;=2). Examples: Input : arr[] = {3, 5, 2, 3, 5, 3, 5} Output : Minimum Distance = 2 Explanation : Greatest element is 5 and its index are 1, 4 and 6. Resulting minimum distan
5 min read
Minimum and maximum count of elements at D distance from arr[i] in either direction
Given a sorted array arr[] and a positive integer D, the task is to find the minimum and the maximum number of array elements that lie over the distance of D from an array element arr[i] in either direction i.e., over the range [arr[i] - D, arr[i]] or [arr[i], arr[i] + D]. Examples: Input arr[] = {2, 4, 7, 11, 13, 14}, D = 4Output: 1 3Explanation:T
14 min read
Queries to find distance between two nodes of a Binary tree
Given a binary tree, the task is to find the distance between two keys in a binary tree, no parent pointers are given. The distance between two nodes is the minimum number of edges to be traversed to reach one node from other. We have already discussed a method which uses segment tree to reduce the query time to O(logn), here the task is to reduce
15+ min read
Ways to choose three points with distance between the most distant points &lt;= L
Given a set of n distinct points x1, x2, x3... xn all lying on the X-axis and an integer L, the task is to find the number of ways of selecting three points such that the distance between the most distant points is less than or equal to L Note: Order is not important i.e the points {3, 2, 1} and {1, 2, 3} represent the same set of three points Exam
15+ min read
Puzzle | Minimum distance for Lizard
A lizard is present on one corner of cube, It wants to reach diagonally opposite corner of cube. You have to calculate minimum distance lizard has to cover to reach its destination.Note : Lizard can't fly, it moves along the wall.You are given a representing side of cube.you have to calculate minimum distance lizard has to travel. Examples: Input :
3 min read
Count number of steps to cover a distance if steps can be taken in powers of 2
Given a distance K to cover, the task is to find the minimum steps required to cover the distance if steps can be taken in powers of 2 like 1, 2, 4, 8, 16........Examples : Input : K = 9 Output : 2 Input : K = 343 Output : 6 The minimum steps required can be calculated by reducing K by the highest power of 2 in each step which can be obtained by co
3 min read
Program to calculate distance between two points in 3 D
Given two coordinates (x1, y1, z1) and (x2, y2, z2) in 3 dimension. The task is to find the distance between them.Examples : Input: x1, y1, z1 = (2, -5, 7) x2, y2, z1 = (3, 4, 5) Output: 9.2736184955 Input: x1, y1, z1 = (0, 0, 0) x2, y2, z1 = (1, 1, 1) Output: 1.73205080757 Approach: The formula for distance between two points in 3 dimension i.e (x
5 min read
Perpendicular distance between a point and a Line in 2 D
Given a point (x1, y1) and a line (ax + by + c = 0). The task is to find the perpendicular distance between the given point and the line. Examples : Input: x1 = 5, y1 = 6, a = -2, b = 3, c = 4 Output:3.32820117735Input: x1 = -1, y1 = 3, a = 4, b = -3, c = - 5 Output:3.6 Approach: The distance (i.e shortest distance) from a given point to a line is
9 min read
Distance between a point and a Plane in 3 D
You are given a points (x1, y1, z1) and a plane a * x + b * y + c * z + d = 0. The task is to find the perpendicular(shortest) distance between that point and the given Plane. Examples : Input: x1 = 4, y1 = -4, z1 = 3, a = 2, b = -2, c = 5, d = 8 Output: Perpendicular distance is 6.78902858227Input: x1 = 2, y1 = 8, z1 = 5, a = 1, b = -2, c = -2, d
6 min read
Haversine formula to find distance between two points on a sphere
The Haversine formula calculates the shortest distance between two points on a sphere using their latitudes and longitudes measured along the surface. It is important for use in navigation. The haversine can be expressed in trigonometric function as: [Tex]haversine(\theta)=sin^2\Big(\frac{\theta}{2}\Big) [/Tex]The haversine of the central angle (wh
5 min read
Distance between two parallel Planes in 3-D
You are given two planes P1: a1 * x + b1 * y + c1 * z + d1 = 0 and P2: a2 * x + b2 * y + c2 * z + d2 = 0. The task is to write a program to find distance between these two Planes. Examples : Input: a1 = 1, b1 = 2, c1 = -1, d1 = 1, a2 = 3, b2 = 6, c2 = -3, d2 = -4 Output: Distance is 0.952579344416 Input: a1 = 1, b1 = 2, c1 = -1, d1 = 1, a2 = 1, b2
8 min read
Hammered distance between N points in a 2-D plane
Given n number of point in 2-d plane followed by Xi, Yi describing n points. The task is to calculate the hammered distance of n points. Note: Hammered distance is the sum of the square of the shortest distance between every pair of the point. Examples: Input: n = 30 10 01 0Output: 4 Input: n = 41 02 03 04 0Output: 20 Basic Approach:As we have to f
10 min read