**Example:**

x = 2, y= 5, z = 3 Output: (2 ^ 5) % 3 = 2 x = 5, y= 55, z = 221 Output: (5 ^ 55) % 221 = 112

**Approach:**

Straight forward way to calculate the x^y and then do the MOD with z but there is a problem with this approach. If x^y is big enough to cross the boundary of Integer.MAX then we cannot calculate. Instead, it can do the MOD at each step in the calculation of x^y. This will not change our final result. Let’s see why?

x = 2, y = 8, z = 72^8 = 256%7 = 4Let's see at each step 2^1 = 2 % 7 = 2 2^2 = 2*2 % 7 = 4 2^3 = 4*2 % 7 = 1 (8%7=1) 2^4 = 1*2 % 7 = 2 2^5 = 2*2 % 7 = 4 2^6 = 4*2 % 7 = 1 (8%7=1) 2^7 = 2 % 7 = 2 2^8 = 2*2 % 7 = 4

As we can see, doing MOD at each step will not affect the final result. Now for calculating x^y, the easiest way is multiply x, y times but this will have time complexity O(y), this can be reduced to O(logy) – please refer – calculate power(k,n).

**Complete Code:**

**Output:**

(2 ^ 8) % 7 = 4]]>

**Example:**

A = "horizon" B = "abhordizaonr" Output: true A = "abhordizaonr" B = "horizon" Output: true A = "abhor dizaonr" B = "horizon" Output: true A = "abordizaonr" B = "horizon" Output: false

**Approach: **

- Given strings, A and B.
- Check if any of the string is null, return false.
- Compare the lengths of both the strings
- do String
= A or B, whichever is longer than other.*longer* - do String
= A or B, whichever is shorter than other.*shorter*

- do String
- Now have two strings,
and*longer*. We know only a shorter string can be a subsequence of a longer string, whereas vice versa is not true.*shorter* - Initialize the starting index for the
string as*shorter*.*j = 0* - Iterate the
string and for current index*longer**i*- If the character at index
in*i*is the same as the character at index*longer*in*j*. If yes then do*shorter*.*j++*

- If the character at index
- After iteration, if
means is subsequence in longer string, return true else return false.*j==length of shorter*

**Complete Code:**

**Output:**

true true]]>

**Example:**

Input: [Algorithms, String, Integer, Integer, Algorithms, String, Integer, Algorithms, String, Algorithms] Most frequent word: Algorithms

**Naive Approach: **Use the nested loops, compare the word from the outer loop with all the other elements using the inner loop, and count its appearances. Keep track of the word which appears the maximum number of times.

Time Complexity: O(N^{2})

**Better Approach: Use Map.**

Iterate the array and construct a hashmap with the word as the key and its appearances count as value.

Iterate the hashmap and pick the word with the maximum count.

Time Complexity: O(N), Space Complexity: O(N)

import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class MostFrequentWord { public static String findFrequentWord(String [] input){ System.out.println("Input: " + Arrays.toString(input)); Map<String, Integer> map = new HashMap<>(); for (int i = 0; i <input.length ; i++) { String word = input[i]; int count = map.getOrDefault(word, 0); map.put(word, count+1); } String frequentWord=null; int count = 0; for (String key:map.keySet()){ if(count<map.get(key)){ count = map.get(key); frequentWord = key; } } return frequentWord; } public static void main(String[] args) { String [] input = {"Algorithms", "String", "Integer", "Integer", "Algorithms", "String", "Integer", "Algorithms", "String", "Algorithms"}; System.out.println("Most frequent word: " + findFrequentWord(input)); } }

**Output:**

Input: [Algorithms, String, Integer, Integer, Algorithms, String, Integer, Algorithms, String, Algorithms] Most frequent word: Algorithms]]>

**Note: **All the items weight is less than equal to K.

**Example:**

Items = [2, 3, 1, 5, 3, 6, 2, 2] K = 6 Output: [2, 2, 2] [3, 3] [5, 1] [6] Minimum Trips for robot: 4 Items = [2, 3, 1, 5, 3, 6, 2, 2] K = 10 Output: [6, 1, 2] [5, 3, 2] [3, 2] Minimum Trips for Robot: 3

**Approach: Sorting**.

- Initialize
= 0.*current_weight* - Sort all the items in ascending order.
- Picking elements from right to left and keep adding the weights to
until*current_weight*.*current_weight<K* - Now start picking elements from left to right and adding the weights to
until*current_weight*.*current_weight<K* - Once the previous two steps are over, either
or*current_weight = K*. Send the robot with picked items and add one to trips.*current_weight<K* - Repeat the above steps until all the items are sent.
- Use
to mark if the item is already sent or not.*visited []* - Use a list to track the items sent in each trip.

**Complete Code:**

**Output:**

[6] [5, 1] [3, 3] [2, 2, 2] Minimum Trips for Robot: 4]]>

- Each job duration is 1 unit.
**Name**– Name of the job.**Deadline**– Job should be completed before the deadline is over. For instance if the deadline is 4 then the job has to be completed before 4 time units are over.**Profit**– Amount earned if the job has run.

**Example:**

Jobs Deadline ProfitA 2 40 B 1 20 C 4 10 D 1 10 Output: Jobs: B A C, Total Profit: 70Jobs Deadline ProfitA 2 140 B 1 90 C 2 100 D 3 50 E 3 15 Output: Job Sequence: C A D, Total Profit: 290

**Approach:** Greedy Algorithm

- Sort the jobs in descending order of profit.
- Initialize the result, this will store jobs.
- Iterate through all the jobs (from highest profit to lowest), for job
*j*- Pick the job
if this job can be fit into the result without missing the deadline or in other words if current job*j*does not have any conflict with the jobs already selected in the results.(First job will not have conflict) then job*j*to the result. If job j has conflict then ignore this job.*j*

- Pick the job

**Complete Code:**

**Output:**

Jobs: C A D , Total Profit: 290]]>

**Note: **This problem is an extension of – find the subarray with sum to a Given Value, in which arrays with negative numbers are not handled.

**Example:**

Given input: [25, 12, -14, 22, -19, 15, -10, 23] K = -11. Subarray with sum = -11 Output: [-14 22 -19 ] Given input: [10, 0, -1, 20, 25, 30] K = 45 Subarray with sum = 45 Output: [20 25]

**Approach: **

Given : input[] and K

**Idea:** We need to find subarray input[a, b] – sum of elements from index a to b = K.

input[a, b] = input[0, b] – input[0, a-1]

**Steps:**

- Initialize a
**map**which will store the sum up to element at the current index and current index as a value. - Initialize i = 0, j = -1.
- Initialize curr_sum = 0, keep adding elements during iteration.
- Iterate through array and for currency index
**n**–- curr_sum = curr_sum + input[
**n**]. - Check if curr_sum = K, we have found a subarray and means all the elements till the current element are included, do
**j = k**, and break the loop. - Check if the map contains curr_sum – K, if yes then we have found a subarray, get the index from the map for key curr_sum – K and do
**i = index + 1**and**j= k**, the elements from index**i**to**j**will have sum = k.

- curr_sum = curr_sum + input[
- Check if j!=-1, means we have found the subarray during iteration. Print the elements from index
to index*i*. (*j*), else if j==-1 then no subarray exists with sum = K.*input[i, j]*

Time Complexity: O(N), Space Complexity: O(N)

**Complete Code:**

**Output:**

Given input: [25, 12, 14, 22, 19, 15, 10, 23] Subarray with sum = 55 14 22 19 -------------------------------- Given input: [25, 12, -14, 22, -19, 15, -10, 23] Subarray with sum = -11 -14 22 -19 -------------------------------- Given input: [10, 0, -1, 20, 25, 30] Subarray with sum = 45 20 25]]>

**Example:**

Given Array: [[5, 12, 17, 21, 23] [1, 2, 4, 6, 8] [12, 14, 18, 19, 27] [3, 7, 9, 15, 25]] Sorted Array: [[1, 2, 3, 4, 5] [6, 7, 8, 9, 12] [12, 14, 15, 17, 18] [19, 21, 23, 25, 27]]

**Approach:**

- Each row is sorted, we will take advantage of this.
- Since each row is sorted which means the first column for each row will have the minimum element among their respective rows, which also means that minimum element in the entire matrix will be from the first column. So we will pick that smallest element and replace it with the first element in the matrix.
- Now we have successfully placed the right element at the first position in the array. Now we will restore the original property of the array which is each row is sorted. So we will shift the swapped element (earlier with the first position of the matrix) till it finds its right place in the array.
- Now we need to find the second most minimum element for the second position which will be among elements at the second column in the first row and first column in the rest of the rows. Once found, swap it and again reorder to restore the original property.
- Repeat this process until the entire array is sorted.

See the example below for more understanding-

**Complete Code:**

**Output:**

Given Array: Given Array: 5 12 17 21 23 1 2 4 6 8 12 14 18 19 27 3 7 9 15 25 Sorted Array: 1 2 3 4 5 6 7 8 9 12 12 14 15 17 18 19 21 23 25 27]]>

**put(key, value)**– puts the value again the key in the latest version of the map**get(key)**– get the value of the key for the latest version of the data**snapshot()**– take a snapshot and increment the version**getValVersion(version id, key)**– return value of the key of the particular version**getCurrentVersion()**– return the latest/current version

**Example:**

Operations put("memory", "16GB") put("os_version", "10") put("graphics", "intel_10_153") snapshot() put("os_version", "11") put("graphics", "intel_11_153") get("graphics")) getCurrentVersion()) getValVersion(0, "graphics")) get("os_version"))Output:graphics in current version: intel_11_153 Current Control Map version is : 1 graphics in version 0 : intel_10_153 os_version in current version: 11

**Approach: Use Map of maps**

- The first map will have the version of the control map system as key and the second map as value.
- The second map will store the key-value pairs of attributes of a particular version of the control map.
- Integer currentVersion will represent the latest version at any point of time.
**put(key, value) –**Insert a key-value pair in the second map against the current_version in the first map.**get(key) –**Get the value from the second map for the given**key**against the current_version in the first map**snapshot() –**do old_version = current_version. Increment the current_version by 1 and then insert all the values from old_version to current_version.**getValVersion(version_id, key) –**Get the value from the second map for the given**key**against the**version_id**in the first map. If**version_id**does not exist, print the error message.**getCurrentVersion()**– return the current_version.

**Complete Code:**

**Output:**

Initializing Version Control Map System graphics in current version: intel_11_153 Current Control Map version is : 1 graphics in version 0 : intel_10_153 os_version in current version: 11

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

**Example:**

Given array: [1, 5, 7, 1, -1], Sum= 6 Total Pairs: 3 Note: pairs are (1, 5), (5, 1) and (7, -1) Given array: [4, 5, 1, 2, 9, -2, -4], Sum= 5 Total Pairs: 2 Note: pairs are (4, 1) and (9, -4) Given array: [3, 3, 3, 3], Sum= 6 Total Pairs: 6

**Approach:**

Naive approach to run the nested loops and add each pair to check it with the given sum.

Time Complexity: O(N^{2})

Better approach is to use the Map.

- Traverse the array and construct a map with elements in the array as key and their count as value.
- Initialize pairCount = 0.
- Now traverse the map and for each key
in map with count>0*X*- Do
= sum –*Y*, check if Y is present in map and count>0 , if yes then get the*X*and*X*counts from map.*Y* - Let’s say
is count of*X_COUNT*and*X*is count of*Y_COUNT*.*Y* - If
and*X*are same means both elements are same then do pairCount +*Y*(Number of ways to pick 2 elements out of n = nC2)*X_COUNT*(X_COUNT-1)/2.* - If
and*X*are not same then Do pairCount = pairCount +*Y*.*X_COUNT*Y_COUNT* - Put
and*X*count 0 in the map.*Y*

- Do
- Return pairCount.

Time Complexity: O(N), Space Complexity: O(N)

**Complete Code**

**Output:**

Given array: [1, 5, 7, 1, -1], Sum= 6 Total Pairs: 3]]>

**Example:**

Given Map: Joe : 1000 Earl : 1200 Carl : 2000 Brad : 1510 Dow : 500 Sorted Map: Carl : 2000 Brad : 1510 Earl : 1200 Joe : 1000 Dow : 500

**Approach:**

- Construct the List out of the given Map of type Map.Entry<String, Integer>.
- Sort the list by overriding the compare function in Comparator. Inside compare function – compare the map values.
- Initialize the LinkedHashMap (now order matters since we are sorting the list).
- Iterate the list and fill the linked hash map

**Complete Code:**

**Output:**

Given Map: Joe : 1000 Earl : 1200 Carl : 2000 Brad : 1510 Dow : 500 Sorted Map: Carl : 2000 Brad : 1510 Earl : 1200 Joe : 1000 Dow : 500]]>