The Wayback Machine - https://web.archive.org/web/20241128103217/https://www.geeksforgeeks.org/hopcroft-karp-algorithm-for-maximum-matching-set-2-implementation/
Open In App

Hopcroft–Karp Algorithm for Maximum Matching | Set 2 (Implementation)

Last Updated : 08 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

We strongly recommend to refer below post as a prerequisite.
Hopcroft–Karp Algorithm for Maximum Matching | Set 1 (Introduction)

There are few important things to note before we start implementation. 

  1. We need to find an augmenting path (A path that alternates between matching and not matching edges and has free vertices as starting and ending points).
  2. Once we find the augmenting path, we need to add the found path to the existing Matching. Here adding a path means, making previous matching edges on this path as not-matching and previous not-matching edges as matching.

The idea is to use BFS (Breadth First Search) to find augmenting paths. Since BFS traverses level by level, it is used to divide the graph in layers of matching and not matching edges. A dummy vertex NIL is added that is connected to all vertices on the left side and all vertices on the right side. The following arrays are used to find augmenting paths. Distance to NIL is initialized as INF (infinite). If we start from a dummy vertex and come back to it using alternating paths of distinct vertices, then there is an augmenting path.

  1. pairU[]: An array of size m+1 where m is the number of vertices on the left side of the Bipartite Graph. pairU[u] stores paa r of u on the right side if u is matched and NIL otherwise.
  2. pairV[]: An array of size n+1 where n is several vertices on the right side of the Bipartite Graph. pairV[v] stores a pair of v on the left side if v is matched and NIL otherwise.
  3. dist[]: An array of size m+1 where m is several vertices on the left side of the Bipartite Graph. dist[u] is initialized as 0 if u is not matching and INF (infinite) otherwise. dist[] of NIL is also initialized as INF

Once an augmenting path is found, DFS (Depth First Search) is used to add augmenting paths to current matching. DFS simply follows the distance array setup by BFS. It fills values in pairU[u] and pairV[v] if v is next to u in BFS. 

Below is the implementation of above Hopkroft Karp algorithm.

Java




import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
 
class GFG{
 
static final int NIL = 0;
static final int INF = Integer.MAX_VALUE;
 
static class BipGraph
{
    int m, n;
    List<Integer>[] adj;
    int[] pairU, pairV, dist;
    int hopcroftKarp()
    {
        pairU = new int[m + 1];
        pairV = new int[n + 1];
        dist = new int[m + 1];
        Arrays.fill(pairU, NIL);
        Arrays.fill(pairV, NIL);
        int result = 0;
        while (bfs())
        {
          
            for(int u = 1; u <= m; u++)
             
                if (pairU[u] == NIL && dfs(u))
                    result++;
        }
        return result;
    }
    boolean bfs()
    {
      
        Queue<Integer> Q = new LinkedList<>();
 
        for(int u = 1; u <= m; u++)
        {
            if (pairU[u] == NIL)
            {
                 
                dist[u] = 0;
                Q.add(u);
            }
 
            else
                dist[u] = INF;
        }
        dist[NIL] = INF;
 
        while (!Q.isEmpty())
        {
            int u = Q.poll();
            if (dist[u] < dist[NIL])
            {
                for(int i : adj[u])
                {
                    int v = i;
                    if (dist[pairV[v]] == INF)
                    {
                        dist[pairV[v]] = dist[u] + 1;
                        Q.add(pairV[v]);
                    }
                }
            }
        }
        return (dist[NIL] != INF);
    }
    boolean dfs(int u)
    {
        if (u != NIL)
        {
            for(int i : adj[u])
            {
                int v = i;
                if (dist[pairV[v]] == dist[u] + 1)
                {
                    if (dfs(pairV[v]) == true)
                    {
                        pairV[v] = u;
                        pairU[u] = v;
                        return true;
                    }
                }
            }
            dist[u] = INF;
            return false;
        }
        return true;
    }
 
    // Constructor
    @SuppressWarnings("unchecked")
    public BipGraph(int m, int n)
    {
        this.m = m;
        this.n = n;
        adj = new ArrayList[m + 1];
        Arrays.fill(adj, new ArrayList<>());
    }
    void addEdge(int u, int v)
    {
        adj[u].add(v);
    }
}
public static void main(String[] args)
{
     
    BipGraph g = new BipGraph(4, 4);
    g.addEdge(1, 2);
    g.addEdge(1, 3);
    g.addEdge(2, 1);
    g.addEdge(3, 2);
    g.addEdge(4, 2);
    g.addEdge(4, 4);
 
    System.out.println("Size of maximum matching is " +
                       g.hopcroftKarp());
}
}


C#




// GFG
// C# code for this approach
using System;
using System.Collections.Generic;
using System.Linq;
 
class HopcroftKarp
{
    const int NIL = 0;
    const int INF = int.MaxValue;
 
    static void Main()
    {
        int n = 4; // number of nodes in set U
        int m = 4; // number of nodes in set V
 
        var g = new BipGraph(n, m);
        g.addEdge(1, 2);
        g.addEdge(1, 3);
        g.addEdge(2, 1);
        g.addEdge(3, 2);
        g.addEdge(4, 2);
        g.addEdge(4, 4);
 
        Console.WriteLine("Size of maximum matching is " +
                           g.hopcroftKarp());
    }
 
    class BipGraph
    {
        private readonly int m;
        private readonly int n;
        private readonly List<int>[] adj;
        private int[] pairU;
        private int[] pairV;
        private int[] dist;
 
        public BipGraph(int m, int n)
        {
            this.m = m;
            this.n = n;
            adj = new List<int>[m + 1];
            for (int i = 0; i <= m; i++)
            {
                adj[i] = new List<int>();
            }
        }
 
        public void addEdge(int u, int v)
        {
            adj[u].Add(v);
        }
 
        public int hopcroftKarp()
        {
            pairU = Enumerable.Repeat(NIL, m + 1).ToArray();
            pairV = Enumerable.Repeat(NIL, n + 1).ToArray();
            dist = Enumerable.Repeat(0, m + 1).ToArray();
 
            int result = 0;
            while (bfs())
            {
                for (int u = 1; u <= m; u++)
                {
                    if (pairU[u] == NIL && dfs(u))
                    {
                        result++;
                    }
                }
            }
            return result;
        }
 
        private bool bfs()
        {
            var Q = new Queue<int>();
 
            for (int u = 1; u <= m; u++)
            {
                if (pairU[u] == NIL)
                {
                    dist[u] = 0;
                    Q.Enqueue(u);
                }
                else
                {
                    dist[u] = INF;
                }
            }
            dist[NIL] = INF;
 
            while (Q.Count > 0)
            {
                int u = Q.Dequeue();
                if (dist[u] < dist[NIL])
                {
                    foreach (int v in adj[u])
                    {
                        if (dist[pairV[v]] == INF)
                        {
                            dist[pairV[v]] = dist[u] + 1;
                            Q.Enqueue(pairV[v]);
                        }
                    }
                }
            }
            return dist[NIL] != INF;
        }
 
        private bool dfs(int u)
        {
            if (u != NIL)
            {
                foreach (int v in adj[u])
                {
                    if (dist[pairV[v]] == dist[u] + 1)
                    {
                        if (dfs(pairV[v]))
                        {
                            pairV[v] = u;
                            pairU[u] = v;
                            return true;
                        }
                    }
                }
                dist[u] = INF;
                return false;
            }
            return true;
        }
    }
}
// Thic is written by Sundaram


Javascript




// Javascript implementation of Hopcroft Karp algorithm for maximum matching
 
class BipGraph {
  constructor(m, n) {
    this.__m = m;
    this.__n = n;
    this.__adj = [...Array(m + 1)].map(() => []);
  }
 
  addEdge(u, v) {
    this.__adj[u].push(v); // Add u to v’s list.
  }
 
  bfs() {
    const Q = [];
    for (let u = 1; u <= this.__m; u++) {
      if (this.__pairU[u] === NIL) {
        this.__dist[u] = 0;
        Q.push(u);
      } else {
        this.__dist[u] = INF;
      }
    }
    this.__dist[NIL] = INF;
    while (Q.length > 0) {
      const u = Q.shift();
      if (this.__dist[u] < this.__dist[NIL]) {
        for (const v of this.__adj[u]) {
          if (this.__dist[this.__pairV[v]] === INF) {
            this.__dist[this.__pairV[v]] = this.__dist[u] + 1;
            Q.push(this.__pairV[v]);
          }
        }
      }
    }
    return this.__dist[NIL] !== INF;
  }
 
  dfs(u) {
    if (u !== NIL) {
      for (const v of this.__adj[u]) {
        if (this.__dist[this.__pairV[v]] === this.__dist[u] + 1) {
          if (this.dfs(this.__pairV[v])) {
            this.__pairV[v] = u;
            this.__pairU[u] = v;
            return true;
          }
        }
      }
      this.__dist[u] = INF;
      return false;
    }
    return true;
  }
 
  hopcroftKarp() {
    this.__pairU = Array(this.__m + 1).fill(0);
    this.__pairV = Array(this.__n + 1).fill(0);
    this.__dist = Array(this.__m + 1).fill(0);
    let result = 0;
    while (this.bfs()) {
      for (let u = 1; u <= this.__m; u++) {
        if (this.__pairU[u] === NIL && this.dfs(u)) {
          result++;
        }
      }
    }
    return result;
  }
}
 
const INF = 2147483647;
const NIL = 0;
 
// Driver Program
const g = new BipGraph(4, 4);
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(2, 1);
g.addEdge(3, 2);
g.addEdge(4, 2);
g.addEdge(4, 4);
console.log(`Size of maximum matching is ${g.hopcroftKarp()}`);


C++14




// C++ implementation of Hopcroft Karp algorithm for
// maximum matching
#include<bits/stdc++.h>
using namespace std;
#define NIL 0
#define INF INT_MAX
 
// A class to represent Bipartite graph for Hopcroft
// Karp implementation
class BipGraph
{
    // m and n are number of vertices on left
    // and right sides of Bipartite Graph
    int m, n;
 
    // adj[u] stores adjacents of left side
    // vertex 'u'. The value of u ranges from 1 to m.
    // 0 is used for dummy vertex
    list<int> *adj;
 
    // These are basically pointers to arrays needed
    // for hopcroftKarp()
    int *pairU, *pairV, *dist;
 
public:
    BipGraph(int m, int n); // Constructor
    void addEdge(int u, int v); // To add edge
 
    // Returns true if there is an augmenting path
    bool bfs();
 
    // Adds augmenting path if there is one beginning
    // with u
    bool dfs(int u);
 
    // Returns size of maximum matching
    int hopcroftKarp();
};
 
// Returns size of maximum matching
int BipGraph::hopcroftKarp()
{
    // pairU[u] stores pair of u in matching where u
    // is a vertex on left side of Bipartite Graph.
    // If u doesn't have any pair, then pairU[u] is NIL
    pairU = new int[m+1];
 
    // pairV[v] stores pair of v in matching. If v
    // doesn't have any pair, then pairU[v] is NIL
    pairV = new int[n+1];
 
    // dist[u] stores distance of left side vertices
    // dist[u] is one more than dist[u'] if u is next
    // to u'in augmenting path
    dist = new int[m+1];
 
    // Initialize NIL as pair of all vertices
    for (int u=0; u<=m; u++)
        pairU[u] = NIL;
    for (int v=0; v<=n; v++)
        pairV[v] = NIL;
 
    // Initialize result
    int result = 0;
 
    // Keep updating the result while there is an
    // augmenting path.
    while (bfs())
    {
        // Find a free vertex
        for (int u=1; u<=m; u++)
 
            // If current vertex is free and there is
            // an augmenting path from current vertex
            if (pairU[u]==NIL && dfs(u))
                result++;
    }
    return result;
}
 
// Returns true if there is an augmenting path, else returns
// false
bool BipGraph::bfs()
{
    queue<int> Q; //an integer queue
 
    // First layer of vertices (set distance as 0)
    for (int u=1; u<=m; u++)
    {
        // If this is a free vertex, add it to queue
        if (pairU[u]==NIL)
        {
            // u is not matched
            dist[u] = 0;
            Q.push(u);
        }
 
        // Else set distance as infinite so that this vertex
        // is considered next time
        else dist[u] = INF;
    }
 
    // Initialize distance to NIL as infinite
    dist[NIL] = INF;
 
    // Q is going to contain vertices of left side only.
    while (!Q.empty())
    {
        // Dequeue a vertex
        int u = Q.front();
        Q.pop();
 
        // If this node is not NIL and can provide a shorter path to NIL
        if (dist[u] < dist[NIL])
        {
            // Get all adjacent vertices of the dequeued vertex u
            list<int>::iterator i;
            for (i=adj[u].begin(); i!=adj[u].end(); ++i)
            {
                int v = *i;
 
                // If pair of v is not considered so far
                // (v, pairV[V]) is not yet explored edge.
                if (dist[pairV[v]] == INF)
                {
                    // Consider the pair and add it to queue
                    dist[pairV[v]] = dist[u] + 1;
                    Q.push(pairV[v]);
                }
            }
        }
    }
 
    // If we could come back to NIL using alternating path of distinct
    // vertices then there is an augmenting path
    return (dist[NIL] != INF);
}
 
// Returns true if there is an augmenting path beginning with free vertex u
bool BipGraph::dfs(int u)
{
    if (u != NIL)
    {
        list<int>::iterator i;
        for (i=adj[u].begin(); i!=adj[u].end(); ++i)
        {
            // Adjacent to u
            int v = *i;
 
            // Follow the distances set by BFS
            if (dist[pairV[v]] == dist[u]+1)
            {
                // If dfs for pair of v also returns
                // true
                if (dfs(pairV[v]) == true)
                {
                    pairV[v] = u;
                    pairU[u] = v;
                    return true;
                }
            }
        }
 
        // If there is no augmenting path beginning with u.
        dist[u] = INF;
        return false;
    }
    return true;
}
 
// Constructor
BipGraph::BipGraph(int m, int n)
{
    this->m = m;
    this->n = n;
    adj = new list<int>[m+1];
}
 
// To add edge from u to v and v to u
void BipGraph::addEdge(int u, int v)
{
    adj[u].push_back(v); // Add u to v’s list.
}
 
// Driver Program
int main()
{
    BipGraph g(4, 4);
    g.addEdge(1, 2);
    g.addEdge(1, 3);
    g.addEdge(2, 1);
    g.addEdge(3, 2);
    g.addEdge(4, 2);
    g.addEdge(4, 4);
 
    cout << "Size of maximum matching is " << g.hopcroftKarp();
 
    return 0;
}


Python3




# Python3 implementation of Hopcroft Karp algorithm for
# maximum matching
from queue import Queue
 
INF = 2147483647
NIL = 0
 
# A class to represent Bipartite graph for Hopcroft
# 3 Karp implementation
class BipGraph(object):
    # Constructor
    def __init__(self, m, n):
        # m and n are number of vertices on left
        # and right sides of Bipartite Graph
        self.__m = m
        self.__n = n
        # adj[u] stores adjacents of left side
        # vertex 'u'. The value of u ranges from 1 to m.
        # 0 is used for dummy vertex
        self.__adj = [[] for _ in range(m+1)]
 
    # To add edge from u to v and v to u
    def addEdge(self, u, v):
        self.__adj[u].append(v)  # Add u to v’s list.
 
    # Returns true if there is an augmenting path, else returns
    # false
    def bfs(self):
        Q = Queue()
        # First layer of vertices (set distance as 0)
        for u in range(1, self.__m+1):
            # If this is a free vertex, add it to queue
            if self.__pairU[u] == NIL:
                # u is not matched3
                self.__dist[u] = 0
                Q.put(u)
            # Else set distance as infinite so that this vertex
            # is considered next time
            else:
                self.__dist[u] = INF
        # Initialize distance to NIL as infinite
        self.__dist[NIL] = INF
        # Q is going to contain vertices of left side only.
        while not Q.empty():
            # Dequeue a vertex
            u = Q.get()
            # If this node is not NIL and can provide a shorter path to NIL
            if self.__dist[u] < self.__dist[NIL]:
                # Get all adjacent vertices of the dequeued vertex u
                for v in self.__adj[u]:
                    #  If pair of v is not considered so far
                    # (v, pairV[V]) is not yet explored edge.
                    if self.__dist[self.__pairV[v]] == INF:
                        # Consider the pair and add it to queue
                        self.__dist[self.__pairV[v]] = self.__dist[u] + 1
                        Q.put(self.__pairV[v])
        # If we could come back to NIL using alternating path of distinct
        # vertices then there is an augmenting path
        return self.__dist[NIL] != INF
 
    # Returns true if there is an augmenting path beginning with free vertex u
    def dfs(self, u):
        if u != NIL:
            # Get all adjacent vertices of the dequeued vertex u
            for v in self.__adj[u]:
                if self.__dist[self.__pairV[v]] == self.__dist[u] + 1:
                    # If dfs for pair of v also returns true
                    if self.dfs(self.__pairV[v]):
                        self.__pairV[v] = u
                        self.__pairU[u] = v
                        return True
            # If there is no augmenting path beginning with u.
            self.__dist[u] = INF
            return False
        return True
 
    def hopcroftKarp(self):
        # pairU[u] stores pair of u in matching where u
        # is a vertex on left side of Bipartite Graph.
        # If u doesn't have any pair, then pairU[u] is NIL
        self.__pairU = [0 for _ in range(self.__m+1)]
 
        # pairV[v] stores pair of v in matching. If v
        # doesn't have any pair, then pairU[v] is NIL
        self.__pairV = [0 for _ in range(self.__n+1)]
 
        # dist[u] stores distance of left side vertices
        # dist[u] is one more than dist[u'] if u is next
        # to u'in augmenting path
        self.__dist = [0 for _ in range(self.__m+1)]
        # Initialize result
        result = 0
 
        # Keep updating the result while there is an
        # augmenting path.
        while self.bfs():
            # Find a free vertex
            for u in range(1, self.__m+1):
                # If current vertex is free and there is
                # an augmenting path from current vertex
                if self.__pairU[u] == NIL and self.dfs(u):
                    result += 1
        return result
 
 
# Driver Program
if __name__ == "__main__":
    g = BipGraph(4, 4)
    g.addEdge(1, 2)
    g.addEdge(1, 3)
    g.addEdge(2, 1)
    g.addEdge(3, 2)
    g.addEdge(4, 2)
    g.addEdge(4, 4)
    print("Size of maximum matching is %d" % g.hopcroftKarp())


Output

Size of maximum matching is 4


Time Complexity : O(√V x E), where E is the number of Edges and V is the number of vertices.
Auxiliary Space : O(V) as we are using extra space for storing u and v.

The above implementation is mainly adopted from the algorithm provided on Wiki page of Hopcroft Karp algorithm.



Previous Article
Next Article

Similar Reads

Hopcroft–Karp Algorithm for Maximum Matching | Set 1 (Introduction)
A matching in a Bipartite Graph is a set of the edges chosen in such a way that no two edges share an endpoint. A maximum matching is a matching of maximum size (maximum number of edges). In a maximum matching, if any edge is added to it, it is no longer a matching. There can be more than one maximum matching for a given Bipartite Graph. We have di
3 min read
Hopcroft–Karp Algorithm in Python
A matching in a Bipartite Graph is a set of edges chosen in such a way that no two edges share an endpoint. A maximum matching is a matching of maximum size (maximum number of edges). In a maximum matching, if any edge is added to it, it is no longer a matching. There can be more than one maximum matching for a given Bipartite Graph. Hopcroft Karp
5 min read
Rabin-Karp algorithm for Pattern Searching in Matrix
Given matrices txt[][] of dimensions m1 x m2 and pattern pat[][] of dimensions n1 x n2, the task is to check whether a pattern exists in the matrix or not, and if yes then print the top most indices of the pat[][] in txt[][]. It is assumed that m1, m2 ? n1, n2 Examples: Input: txt[][] = {{G, H, I, P} {J, K, L, Q} {R, G, H, I} {S, J, K, L} } pat[][]
15+ min read
Count distinct substrings of a string using Rabin Karp algorithm
Given a string, return the number of distinct substrings using Rabin Karp Algorithm. Examples: Input : str = “aba”Output : 5Explanation :Total number of distinct substring are 5 - "a", "ab", "aba", "b" ,"ba" Input : str = “abcd”Output : 10Explanation :Total number of distinct substring are 10 - "a", "ab", "abc", "abcd", "b", "bc", "bcd", "c", "cd",
9 min read
Rabin-Karp Algorithm for Pattern Searching
Given a text T[0. . .n-1] and a pattern P[0. . .m-1], write a function search(char P[], char T[]) that prints all occurrences of P[] present in T[] using Rabin Karp algorithm. You may assume that n > m. Examples: Input: T[] = "THIS IS A TEST TEXT", P[] = "TEST"Output: Pattern found at index 10 Input: T[] = "AABAACAADAABAABA", P[] = "AABA"Output:
15 min read
Karp's minimum mean (or average) weight cycle algorithm
Given a directed and strongly connected graph with non-negative edge weights. We define the mean weight of a cycle as the summation of all the edge weights of the cycle divided by the no. of edges. Our task is to find the minimum mean weight among all the directed cycles of the graph. Example: Input : Below Graph Output : 1.66667 Method to find the
11 min read
Implementation of Chinese Remainder theorem (Inverse Modulo based implementation)
We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: x % num[0] = rem[0], x % num[1] = rem[1], ....................... x % num[k-1] = rem[k-1] Example: Input: num[] = {3, 4, 5}, rem[] = {2, 3, 1} Output: 11 Explanation: 11 is the sm
11 min read
Hungarian Algorithm for Assignment Problem | Set 2 (Implementation)
Given a 2D array, arr of size N*N where arr[i][j] denotes the cost to complete the jth job by the ith worker. Any worker can be assigned to perform any job. The task is to assign the jobs such that exactly one worker can perform exactly one job in such a way that the total cost of the assignment is minimized. Example Input: arr[][] = {{3, 5}, {10,
7 min read
Implementation of Exhaustive Search Algorithm for Set Packing
Exhaustive Search Algorithm: Exhaustive Search is a brute-force algorithm that systematically enumerates all possible solutions to a problem and checks each one to see if it is a valid solution. This algorithm is typically used for problems that have a small and well-defined search space, where it is feasible to check all possible solutions. Exampl
11 min read
Peterson's Algorithm for Mutual Exclusion | Set 1 (Basic C implementation)
Problem: Given 2 processes i and j, you need to write a program that can guarantee mutual exclusion between the two without any additional hardware support. Solution: There can be multiple ways to solve this problem, but most of them require additional hardware support. The simplest and the most popular way to do this is by using Peterson's Algorit
11 min read
Push Relabel Algorithm | Set 2 (Implementation)
We strongly recommend to refer below article before moving on to this article. Push Relabel Algorithm | Set 1 (Introduction and Illustration) Problem Statement:  Given a graph that represents a flow network where every edge has a capacity. Also given two vertices source ‘s’ and sink ‘t’ in the graph, find the maximum possible flow from s to t with
15+ min read
Maximum Bipartite Matching
A matching in a Bipartite Graph is a set of the edges chosen in such a way that no two edges share an endpoint. A maximum matching is a matching of maximum size (maximum number of edges). In a maximum matching, if any edge is added to it, it is no longer a matching. There can be more than one maximum matchings for a given Bipartite Graph. Why do we
15+ min read
Bellman Ford Algorithm (Simple Implementation)
We have introduced Bellman Ford and discussed on implementation here.Input: Graph and a source vertex src Output: Shortest distance to all vertices from src. If there is a negative weight cycle, then shortest distances are not calculated, negative weight cycle is reported.1) This step initializes distances from source to all vertices as infinite an
13 min read
Implementation of Least Recently Used (LRU) page replacement algorithm using Counters
Prerequisite - Least Recently Used (LRU) Page Replacement algorithm Least Recently Used page replacement algorithm replaces the page which is not used recently. Implementation: In this article, LRU is implemented using counters, a ctime (i.e., counter) variable is used to represent the current time, it is incremented for every page of the reference
8 min read
Implementation of Restoring Division Algorithm for unsigned integer
In the previous article, we have already discussed the Restoring Division Algorithm. In this article, we will discuss the implementation of this algorithm. Restoring Division Algorithm is used to divide two unsigned integers. This algorithm is used in Computer Organization and Architecture. This algorithm is called restoring because it restores the
14 min read
Implementation of Non-Restoring Division Algorithm for Unsigned Integer
In the previous article, we have already discussed the Non-Restoring Division Algorithm. In this article, we will discuss the implementation of this algorithm. Non-restoring division algorithm is used to divide two unsigned integers. The other form of this algorithm is Restoring Division. This algorithm is different from the other algorithm because
15 min read
Implementation of Wu Manber Algorithm?
What is Wu- Manber Algorithm? The Wu-Manber algorithm is a string-matching algorithm that is used to efficiently search for patterns in a body of text. It is a hybrid algorithm that combines the strengths of the Boyer-Moore and Knuth-Morris-Pratt algorithms to provide fast and accurate pattern matching. Illustration: Example: s = "the quick brown f
12 min read
Implementation of Vernam Cipher or One Time Pad Algorithm
One Time Pad algorithm is the improvement of the Vernam Cipher, proposed by An Army Signal Corp officer, Joseph Mauborgne. It is the only available algorithm that is unbreakable(completely secure). It is a method of encrypting alphabetic plain text. It is one of the Substitution techniques which converts plain text into ciphertext. In this mechanis
13 min read
Implementation of Exact Cover Problem and Algorithm X using DLX
In the article Exact Cover Problem and Algorithm X | Set 1 we discussed the Exact Cover problem and Algorithm X to solve the Exact cover problem. In this article, we’ll discuss the implementation details of Algorithm X using Dancing Links Technique (DLX) proposed by Dr Donald E. Knuth in his paper “Dancing Links” Dancing Link Technique Dancing link
10 min read
Implementation of RC4 algorithm
RC4 is a symmetric stream cipher and variable key length algorithm. This symmetric key algorithm is used identically for encryption and decryption such that the data stream is simply XORed with the generated key sequence. The algorithm is serial as it requires successive exchanges of state entries based on the key sequence. The algorithm works in t
15+ min read
Introduction and implementation of Karger's algorithm for Minimum Cut
Given an undirected and unweighted graph, find the smallest cut (smallest number of edges that disconnects the graph into two components). The input graph may have parallel edges. For example consider the following example, the smallest cut has 2 edges. A Simple Solution use Max-Flow based s-t cut algorithm to find minimum cut. Consider every pair
15+ min read
LS3/NS3 sphere generation algorithm and its implementation
Given center of the sphere and its radius. your task is to store efficiently all the integer points required to show a sphere on the computer screen of pixels and This algorithm will generate naive sphere by creating voxels by its naive arcs. NS3 stands for naive sphere by sum of squares and LS3 stands for lattice sphere by sum of squares. Examples
15+ min read
Johnson’s algorithm for All-pairs shortest paths | Implementation
Given a weighted Directed Graph where the weights may be negative, find the shortest path between every pair of vertices in the Graph using Johnson's Algorithm.  The detailed explanation of Johnson's algorithm has already been discussed in the previous post.  Refer Johnson’s algorithm for All-pairs shortest paths.  This post focusses on the impleme
12 min read
Implementation of Johnson’s algorithm for all-pairs shortest paths
Johnson's algorithm finds the shortest paths between all pairs of vertices in a weighted directed graph. It allows some of the edge weights to be negative numbers, but no negative-weight cycles may exist. It uses the Bellman-Ford algorithm to re-weight the original graph, removing all negative weights. Dijkstra's algorithm is applied on the re-weig
14 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Table of Content What is Binary Search Algorithm?Conditions to apply Binary Search Algorithm in a Data St
15+ min read
Longest Common Prefix Matching | Set-6
Given a set of strings, find the longest common prefix. Examples: Input: str[] = {geeksforgeeks, geeks, geek, geezer} Output: gee Input: str[] = {apple, ape, april} Output: ap Previous Approaches: Set1 | Set2 | Set3 | Set4 | Set5 Approach: Sort the given set of N strings.Compare the first and last string in the sorted array of strings.The string wi
6 min read
Count of matching set and unset bits in given integers.
For two integers X and Y are the tasks is to find the number of bits that are the same in their binary representation by not considering any leading zeroes after the leftmost set bit of the greater number in binary form. Examples: Input: X = 10, Y = 6Output: 2Explanation: The binary representation of 10 is 1010 and 6 is 0110. So, the number of same
8 min read
WildCard pattern matching having three symbols ( * , + , ? )
Given a text and a wildcard pattern, implement wildcard pattern matching algorithm that finds if wildcard pattern is matched with text. The matching should cover the entire text (not partial text). The wildcard pattern can include the characters ‘?’, ‘*’ and '+'. ‘?’ – matches any single character ‘*’ – Matches any sequence of characters (including
14 min read
Applications of String Matching Algorithms
String matching algorithms have greatly influenced computer science and play an essential role in various real-world problems. It helps in performing time-efficient tasks in multiple domains. These algorithms are useful in the case of searching a string within another string. String matching is also used in the Database schema, Network systems.Let
5 min read
Difference summation with Array index matching
Given two sorted arrays A and B of size N and M respectively, the task is to find the value V, which is the summation of (A[j] - A[i]) for all pairs of i and j such that (j - i) is present in array B. Examples: Input: N = 4, M = 2, A[] = {1, 2, 3, 4}, B[] = {1, 3}Output: 6Explanation: Valid pairs of (i, j) are (1, 2), (2, 3), (3, 4), (1, 4). So the
7 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg