Given a bipartite graph, write an algorithm to find the maximum matching.

*The maximum bipartite matching solves many problems in the real world like if there are M jobs and N applicants. Each applicant can do some jobs. Your task is to assign these jobs to the applicants so that maximum applicants get the job. Given the condition is one applicant will be assigned one job and vice versa.*

Before we continue solving the problem, first we will understand what is bipartite matching and how we can obtain the maximum matching. If you are new to bipartite graphs, please read about it first here – Introduction to Bipartite Graphs.

**Bipartite Matching-** Matching in the bipartite graph where each edge has unique endpoints or in other words, no edges share any endpoints. For Instance, if there are M jobs and N applicants. Each applicant can do some jobs. In matching one applicant is assigned one job and vice versa. See the example below.

**Maximum Bipartite Matching** – If we have M jobs and N applicants, we assign the jobs to applicants in such a manner that we obtain the maximum matching means, we assign the maximum number of applicants to jobs. Once a maximum match is found, no other edge can be added and if an edge is added it’s no longer matching. There could be more than one maximum matching in a given bipartite graph. Below is the maximum bipartite matching of the example given above.

**Solution: **

**Reduce Bipartite Matching to Flow Network:** We can construct Flow network out of bipartite graph by following steps

- Create a source and a target vertex.
- Add the edges from the source vertex to all the vertices of one set( for example, all applicants) in the bipartite graph.
- Add edges from all the vertices of another set( all jobs) in the bipartite graph to the target vertex.
- Mark the capacity of each edge as 1.
- See the image where the above example is converted into a flow network.

Once the flow network is constructed we can reduce the ** Maximum Bipartite Matching problem** to the

Bipartite graph represented by an adjacency matrix, let’s say it is **adjMatrix[][]**, where the jobs will be represented by rows and applicants will be represented by columns. If an applicant x is can do jobs a, b, c then in matrix **adjMatrix[x][a]=1, adjMatrix[x][b]=1 **and** adjMatrix[x][b]=1, **else it will be **0.**

The simplest solution would be to add a row and column for source and target vertices in the adjacency matrix and follow the Max Flow – Ford-Fulkerson Algorithm to get the maximum flow or in this case, it will be maximum matching as well but this will increase the space complexity. This can be resolved considering that, given the capacities are all 1, we will either use an edge completely (sending 1 unit of flow) or not use an edge at all. Follow the steps below –

- Maintain an assign[] array to keep track of which job is assigned to which applicant. For instance, assign[1]=2 means job number 1 is assigned to applicant number 2.
- Each applicant will maintain a visited[] array to keep track of which jobs the candidate was already considered (to avoid going in loops).
- For each applicant do the Depth-First Search (DFS) (to find a job).
- Iterate through all the jobs and for each job
- check if applicant can do this job and applicant was never considered for this job (adjMatrix[applicant][job] == 1 && visited[job]==false), if yes then mark visited[job]==true (applicant is being considered for this job now and will not be considered again)
- check if the job is not assigned to any other applicant (assign[job]==-1) – then assign the job to this applicant OR If the job was assigned earlier to any other applicant say ‘X’ earlier then make the recursive call for applicant ‘X’ (do another DFS) to check if some other job can be assigned applicant ‘X’ If that happens, assign this job to the current applicant and break the current loop 3a and check for the next applicant. and If this job cannot be assigned to this applicant then check for the next job.

- Iterate through all the jobs and for each job
- See the code above example for better understanding.

**Complete Code:**

**Output:**

Maximum number of applicants that could get jobs are: 6

References –

]]>Say we have a list of employees. Each employee has id, name, and salary. Write a function to print all the employees in ascending order of their names and also find the employee with the maximum salary.

**Example:**

Input:[[0 Carl 10000], [1 Andy 20000], [2 Bob 30000], [3 Drake 5000]]Output:All Employees (Alphabetically) : [[1 Andy 20000], [2 Bob 30000], [0 Carl 10000], [3 Drake 5000]] Employee with highest salary: [2 Bob 30000]

Use Arrays sort method and override the compare function to sort the employee’s array as per the employee name to get the employees sorted with ascending order of names. And to get the employees with the highest salary, override the compare function to sort the employee’s array as per the salary in descending order, and then get the first employee from the array, this employee will have the highest salary.

**Complete Code:**

**Output:**

Given array of employees: [[0 Carl 10000], [1 Andy 20000], [2 Bob 30000], [3 Drake 5000]] [[1 Andy 20000], [2 Bob 30000], [0 Carl 10000], [3 Drake 5000]] Employee with highest salary: [2 Bob 30000]]]>

**Pascal Triangle:**

Note: In Pascal’s triangle, each number is the sum of the two numbers directly above it.

(Image reference: Wiki)

**Approach:**

- Initialize list
and list of lists as*row*.*all_rows* - We will keep updating the list
by adding more numbers and after each iteration, create a copy of the row and add it to the*row*.*all_rows* - How we will update
–*row*- For each iteration of
**N**, add 1 at index 0. Now iterate the rest of the elements in the list,*row*keep adding elements in pairs, starting from j=1, and set the sum at index j.

- For each iteration of
- See the walk-through below

**Complete Code:**

**Output:**

[1] [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1]]]>

**Example:**

Input = "aaaaabbbbb" Output: 1 Explanation: In the input string, characters 'a' and 'b', both occur 5 times. You can delete either one 'a' or one 'b' to make their count unique (4 and 5 or 5 and 4). Input = "abcaabbcdaab" Output: 0 Explanation: count of 'a' = 5 count of 'b' = 4 count of 'c' = c Count of 'd' = 1 All characters count is already unique. Input = "aaaabbbbccccdddd" Output: 6 Explanation: count of 'a' = 4 count of 'b' = 4 count of 'c' = 4 Count of 'd' = 4 Delete 1 'b', 2 'c' and 3 'd' to make unique counts as (4, 3, 2, 1)

**Approach:**

- Construct array count[] which contains a count for each character. Below are the steps to how to construct that array.
- Create an array charCount[] of size 26 and fill with 0.
- Iterate the array and maintain the count of each letter in the array charCount[] so that count of character a, b, c, ,,,,, z will be stored at index 0, 1, 2, ,,,,, 25 respectively.
- Once the iteration is completed copy all the elements with non zero count to array list and convert that list to count[].

- Once count[] is constructed, Sort the count[] in descending order.
- Initialize deletes = 0.
- Iterate the count[] from left to right, for current element i
- Iterate elements from j = i+1 to end and if count[i]==count[j], reduce the count at index j and do deletes++ else break the loop. (array is sorted, so you will not find another index j which is equal to index i).

- Return deletes
- See the walkthrough below for more understanding.

input= "aabbbccc" charCount[] = 2, 3, 3, 0, 0, 0 , , , , , , , , , , 0 (size 26) count[] = 2, 3, 3 Sort the count[] in descending order count[] = 3, 3, 2 deletes = 0 3 = 3, so reduce next 3 to 2, deletes = 1 count[] = 3, 2, 2 2=2, so reduce next 2 to 1, deletes = 2 count[] = 3, 2, 1 All counts are unique. Minimum deletes = 2 Time Complexity: O(n + k^2) Where k = 26 ( no of letters)

**Complete Code:**

**Output:**

Given String: aaaa, Minimum Deletion: 0 Given String: aaabbb, Minimum Deletion: 1 Given String: abcaabbcdaab, Minimum Deletion: 0 Given String: aaaabbbbccccdddd, Minimum Deletion: 6]]>

Tax bracket is a pair consisting of amount and percentage tax on that amount. If amount is null means, it’s a highest bracket and percentage tax is mentioned will be applied to all the remaining income. See the example below for more understanding.

**Example:**

Tax brackets: [10000, 0.10] [20000, 0.20] [15000, 0.30] [null, 0.50] Income: 100,000. total_tax : For First 10000, 10% tax, total_tax = 1000 Next 20000, 20% tax, total_tax = 1000 + 4000 = 5000 Next 15000, 30% tax, total_tax = 5000 + 4500 = 9500 For remaining 55000, 50% tax, total_tax = 27500 + 9500 = 37000.

**Approach:**

- Initialize the taxes as 0.
- bracket_Index = 0.
- while income > 0
- Get the
**tax bracket**at index = bracket_Index. - Get the tax percentage for the picked
**tax bracket**. - If the
**tax bracket limit**is not null then Pick the minimum of (tax bracket limit and income) and multiply it with the tax percentage and add it to the taxes. (why minimum because let’s say income is 6000 and tax bracket is 10000. So we need to calculate the tax only on 6000.) reduce the income by the picked amount and increment the tax_bracket index by 1. - If the
**tax bracket limit**is null then we are at the highest tax bracket, do income * tax percentage.

- Get the
- Return the taxes.

**Complete Code:**

**Output: **

Calculated Taxes: 37000.0 for income: 100000]]>

Write a program to count all valid pickup/delivery possible sequences

Since the answer may be too large, return it modulo 10^9 + 7.

**Example: **

Input: N = 1 Output: 1 Note: (P1, D1), Delivery 1 always is after of Pickup Input: N = 2 Output: 6 Explanation: All possible orders: (P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1). This is an invalid order (P1, D2, P2, D1) because Pickup 2 is after Delivery 2. Input: N = 3 Output: 90

**Approach:**

**Find all permutations:**

Let’s say there are N = 2 orders which means there are two pickups P1, P2 and 2 delivery D1, D2.Lets consider each as an individual event which needs to take place. Permutation of these events happening is !4 = 4x3x2x1 = 24(you have 4 options to pick for the first event, 3 options when picking second option, 2 options for third and only one option for the last one.

**Filter out the invalid ones:**

Now in this 24 sequences we have picked the invalid ones as well like (P1, D2, P2, D1) or (D1, D2, P2, P1). So for each order (P1, D1) is valid and (D1, P1) is invalid. So for each pair we need to divide the permutation by 2 to remove the invalid ones. So for N = 2, we need to divide by 2×2. So our answer would be 24/4 = 4.

So for any N, the final result would be **!2N/****2**** ^{N}**. Keep taking Mod with 10^9 + 7 before the answer gets large.

**Time Complexity:** O(N)

**Complete Code:**

**Output: **

N = 2, Valid pickup/delivery pairs: 6 N = 3, Valid pickup/delivery pairs: 90 N = 7, Valid pickup/delivery pairs: 681080400

**Reference:** Leetcode

**Example:**

Input: [abc : 10] [def : 20] [abc : 15] [ghi : 50] [xyz : 100] [abc : 25] [jkl : 10] [mno : 15] [pqr : 25] [stu : 35] [lko : 19] [aaa : 5] [bbb : 10] [ccc : 35] [abc : 25] [eee : 20]Output:Top videos: [xyz : 100] [abc : 75] [ghi : 50] [ccc : 35] [stu : 35] [pqr : 25] [def : 20] [eee : 20] [lko : 19] [mno : 15]

**Approach:**

- Construct the map from the given list of Video with videoName as key and its watch rate. With this the watch rates will be combined for each video.
- Convert the constructed map to the list of type Map.Entry<String, Integer>.
- Sort the list by overriding the compare function in Comparator. Inside compare function – compare the map values.
- Iterate the list and print the top 10 items from the list.

**Complete Code:**

**Output:**

Top videos: [xyz : 100] [abc : 75] [ghi : 50] [ccc : 35] [stu : 35] [pqr : 25] [def : 20] [eee : 20] [lko : 19] [mno : 15]

**Reference: **https://www.careercup.com/question?id=5713593060818944

**Example:**

Version A: 1.1.0 Version B: 1.1.1 Given version B latest than version A Version A: 1.2.1 Version B: 1.2.1 Given versions are the same Version A: 2.2.0 Version B: 2.2 Given versions are the same Version A: 2.2.0.0.1 Version B: 2.2.0 Given version A latest than version B Version A: 2.2.0.0.1 Version B: 2.2.1 Given version B latest than version A

**Approach: **

Split the versions by ‘.’ and store it in an array. Call the arrays, versions_a[] and versions_b[]. Now iterate both the arrays at the same time and compare the version number from both arrays. During iteration, if at any point if one version number is greater than another we have found which version is the latest, return that. If any of the arrays gets over before another array then traverse the array which is remaining and look for any number greater than 0, if yes then the longer version is the latest one else both versions are the same.

**Complete Code:**

**Output:**

Version A: 1.1.0 Version B: 1.1.1 Given version B latest than version A -------------------------------------------------- Version A: 1.2.1 Version B: 1.2.1 Given versions are the same -------------------------------------------------- Version A: 2.2.0 Version B: 2.2 Given versions are the same -------------------------------------------------- Version A: 2.2.0.0.1 Version B: 2.2.0 Given version A latest than version B -------------------------------------------------- Version A: 2.2.0.0.1 Version B: 2.2.1 Given version B latest than version A -------------------------------------------------- Version A: a.b.c Version B: 2.2.1 Given versions are not valid -------------------------------------------------- Version A: 1. 2.3 Version B: 2.2.1 Given version B latest than version A ------------------------------------------------]]>

**Example:**

Given Input: 34277765 Output: 77765432 Given Input: -342765 Output: -234567 Given Input: 0 Output: 0 Given Input: 2034 Output: 4320

**Approach: Sorting**

Check if the given number is negative and mark isNegative = true or false accordingly.

Get all the digits of the given number and sort these numbers in ascending order if isNegative = true or sort in descending order if isNegative = false. Now construct the number from the sort order. Multiply the final result with -1 if isNegative = true.

**Time Complexity:** O(nlogn)

**Complete Code:**

**Output:**

Given Input: 34277765 Largest Integer can be formed: 77765432 ------------------------------------- Given Input: -342765 Largest Integer can be formed: -234567 ------------------------------------- Given Input: 0 Largest Integer can be formed: 0 ------------------------------------- Given Input: 2034 Largest Integer can be formed: 4320

**Counting Approach:**

- Check if the given number is negative and mark isNegative = true or false accordingly.
- Initialize a count [] array of size 10. (for digits 0 to 9).
- Get all the digits of the given number and store these in count[] with their counts in the given array.
- Initialize int result = 0.
- Now Iterate the array from 0 to 9 (if isNegative=true) or 9 to 0(if isNegative = false) and for each index do the below
- while count[index]>0
- result = result * 10;
- result +=index;
- count[index]–;

- while count[index]>0
- Multiply the final result with -1 if isNegative = true

**Time Complexity:** O(n)

**Complete Code:**

**Output:**

Given Input: 34277765 Largest Integer can be formed: 77765432 ------------------------------------- Given Input: -342765 Largest Integer can be formed: -234567 ------------------------------------- Given Input: 0 Largest Integer can be formed: 0 ------------------------------------- Given Input: 2034 Largest Integer can be formed: 4320]]>

**Example:**

Input[] : [2, 20, 15, 6, 10] Minimums adjacent swaps required sort the array: 5 Input[] : [10, 3, 4, 2, 5, 7, 9, 11] Minimums adjacent swaps required sort the array: 8

**Approach:**

This problem is very similar to find the number of reverse pairs in a given array. All these reverse pairs need to swap in order to sort the array, and that count will be the minimum number of adjacent swaps to sort the array. Let’s take one example. 3, 1, 2. Reverse pairs are 2 [(3, 2) (3, 1)] and adjacent swaps required are 3 [ 3 with 1 and then swap 2 with 1). Why do these count matches? if you notice each swap with reducing one reverse pair, so x swaps will reduce reverse pairs. Like in our example- 3, 1, 2 after first swap 3 with 1. An array would be 1, 3, 2 and there is only one reverse pair which is (3, 2).

**Time Complexity:** O(nlogn)

**Complete Code:**

**Output:**

Input[] : [10, 3, 4, 2, 5, 7, 9, 11] Minimums adjacent swaps required sort the array: 8]]>