Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
20 views10 pages

Ibm 1-4

Uploaded by

Nahemiah Rao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views10 pages

Ibm 1-4

Uploaded by

Nahemiah Rao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

1.

​ Problem: Minimum Moves to Balance Workload

A data center has a number of servers, and each server is handling a certain number of tasks.
The goal is to balance the workload so that every server has the same number of tasks. You
can move a single task from any server to any other server in one move.

Write a function to calculate the minimum total number of tasks that need to be moved to
balance the workload across all servers.

If the workload cannot be evenly distributed among the servers, it's impossible to balance them.
In this case, the function should return -1.

Input Format

●​ An array/list of integers, tasks, where tasks[i] is the number of tasks on the i-th
server.

Output Format

●​ An integer representing the minimum total number of tasks that need to be moved.
●​ Return -1 if the tasks cannot be distributed evenly.

Example

Input: tasks = [3, 2, 7]

Explanation: There are 3 servers with a total of 3+2+7=12 tasks. The balanced state requires
each server to have 12div3=4 tasks.

●​ Server 1 needs 1 task.


●​ Server 2 needs 2 tasks.
●​ Server 3 has an excess of 3 tasks.

The total number of tasks that must be moved out of overloaded servers is 3. Therefore, the
minimum number of moves is 3.

Output: 3

Complete Code
Python
# ===================================================================
# The code below is typically pre-written by the platform (Boilerplate)
# ===================================================================
1 #!/bin/python3
2
3 import math
4 import os
5 import random
6 import re
7 import sys
8
9
10 #
11 # Complete the 'minimumMovesToBalance' function below.
12 #
13 # The function is expected to return an INTEGER.
14 # The function accepts INTEGER_ARRAY tasks as parameter.
15 #
16
17
# ===================================================================
# The code below is the solution you would write.
# ===================================================================
18 def minimumMovesToBalance(tasks):
19 total_tasks = sum(tasks)
20 n = len(tasks)
21
22 if total_tasks % n != 0:
23 return -1
24
25 target = total_tasks // n
26 moves = 0
27 excess = []
28 deficit = []
29
30 for task in tasks:
31 if task > target:
32 excess.append(task - target)
33 elif task < target:
34 deficit.append(target - task)
35
36 # The number of moves is simply the sum of all excesses (or deficits).
37 # The while loop below is one way to calculate it.
38 # A simpler way is: return sum(excess)
39
40 i, j = 0, 0
41 while i < len(excess) and j < len(deficit):
42 transfer = min(excess[i], deficit[j])
43 excess[i] -= transfer
44 deficit[j] -= transfer
45 moves += transfer
46
47 if excess[i] == 0:
48 i += 1
49 if deficit[j] == 0:
50 j += 1
51
52 return moves
53
# ===================================================================
# The code below is also typically pre-written (Boilerplate)
# ===================================================================
54 if __name__ == '__main__':
55 # fptr = open(os.environ['OUTPUT_PATH'], 'w')
56
57 tasks_count = int(input().strip())
58
59 tasks = []
60
61 for _ in range(tasks_count):
62 tasks_item = int(input().strip())
63 tasks.append(tasks_item)
64
65 result = minimumMovesToBalance(tasks)
66
67 print(str(result))
68
69 # fptr.write(str(result) + '\n')
70 # fptr.close()
f course. Here are all three questions retrieved from the images, presented in the same detailed
format as before.

2.​ Diverse Deputations

A professional society is using a program to determine possible diverse deputations of 3


members for an upcoming conference. There are m men and w women who are eligible. A
deputation is diverse only if it contains at least one man and at least one woman.

Two deputations are considered distinct if one has a member that the other does not. Given a
number of men and women, determine the number of distinct ways to select a diverse
deputation of 3 people.

Function Description

Complete the function diverseDeputation in the editor. The function must return an integer
denoting the number of ways to form a diverse deputation.

diverseDeputation has the following parameters:

●​ m: an integer, the number of men.


●​ w: an integer, the number of women.

Example

Input: m = 1 w = 3

Explanation: There is m=1 man (m1) and w=3 women (w1, w2, w3). A diverse deputation must
have 3 people, with at least one of each gender. The only possible compositions are (1 man, 2
women) or (2 men, 1 woman).

●​ Ways to choose 2 men from 1: C(1,2)=0.


●​ Ways to choose 1 man from 1 and 2 women from 3: C(1,1)timesC(3,2)=1times3=3. The
possible deputations are: (m1, w1, w2), (m1, w1, w3), (m1, w2, w3). Total distinct ways =
3.

Output: 3

Complete Code (Java)


Java
// ===================================================================
// The code below is typically pre-written by the platform (Boilerplate)
// ===================================================================
import java.io.*;
// ... other imports

class Result {

/*
* Complete the 'diverseDeputation' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. INTEGER m
* 2. INTEGER w
*/

// ===================================================================
// The code below is the solution you would write.
// ===================================================================
public static int diverseDeputation(int m, int w) {
// A diverse deputation of 3 can be:
// Case 1: 2 men and 1 woman
// Case 2: 1 man and 2 women

long ways_2m_1w = 0;
// Check if we can choose 2 men and 1 woman
if (m >= 2 && w >= 1) {
// Combination formula C(n, k) = n! / (k! * (n-k)!)
// C(m, 2) = m * (m - 1) / 2
// C(w, 1) = w
ways_2m_1w = ((long)m * (m - 1) / 2) * w;
}

long ways_1m_2w = 0;
// Check if we can choose 1 man and 2 women
if (m >= 1 && w >= 2) {
// C(m, 1) = m
// C(w, 2) = w * (w - 1) / 2
ways_1m_2w = m * ((long)w * (w - 1) / 2);
}

return (int)(ways_2m_1w + ways_1m_2w);


}
}
// ===================================================================
// The code below is also typically pre-written (Boilerplate)
// ===================================================================
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(System.in));
// BufferedWriter bufferedWriter = new BufferedWriter(new
FileWriter(System.getenv("OUTPUT_PATH")));

int m = Integer.parseInt(bufferedReader.readLine().strip());
int w = Integer.parseInt(bufferedReader.readLine().strip());

int result = Result.diverseDeputation(m, w);

System.out.println(String.valueOf(result));
// bufferedWriter.write(String.valueOf(result));
// bufferedWriter.newLine();

bufferedReader.close();
// bufferedWriter.close();
}
}

3.​ Binary Tree Nodes

You are given a table, TREE, which contains information about nodes in a tree data structure.
The table has two columns: ID and P_ID, representing a node's ID and its parent's ID,
respectively.

Write a query to identify the ROOT, INNER, and LEAF nodes of the tree. The output should be
the node ID and its TYPE, separated by a space.

Node types are defined as:

●​ LEAF: If the node is not the root of the tree and its ID never appears in the P_ID
column.
●​ ROOT: If the node's P_ID is NULL.
●​ INNER: If the node is neither a LEAF nor a ROOT.
Note that the output should be ordered by the node ID. Also, the output is case-sensitive, so
make sure to output only LEAF, ROOT, or INNER.

Input Format

The TREE table has the following schema:

●​ ID: Integer. A node's ID. This is the primary key.


●​ P_ID: Integer. The ID of the parent node.

Output Format

Two columns, ID and TYPE, ordered by ID.

Complete Code (MySQL)


SQL
-- This is a query, so the entire block is the solution.
SELECT
ID,
CASE
WHEN P_ID IS NULL THEN 'ROOT'
WHEN ID IN (SELECT DISTINCT P_ID FROM TREE WHERE P_ID IS NOT NULL) THEN
'INNER'
ELSE 'LEAF'
END AS TYPE
FROM
TREE
ORDER BY
ID;

4.​ REST API: Country Codes

Given a country name and a phone number, query the API at


https://jsonmock.hackerrank.com/api/countries?name=<country> to get the
country's calling codes.

If there are multiple calling codes for the country, use the one at the highest index in the
callingCodes array. Prepend the calling code to the phone number and return the string. If
the data array in the API response is empty, return the string "-1".
The format of the number should be: "+<Calling Code> <Phone Number>"

API Response Details

The response is a JSON object with 5 fields. The essential field is data.

●​ data: Either an empty array or an array with a single object that contains the country's
record.
○​ In the data array, the country has the following schema:
■​ name: The name of the country (String).
■​ callingCodes: An array of the country's calling codes (Array of Strings).
■​ ... and other fields that are not of interest.

Example

Input: country = "Afghanistan" phoneNumber = "656445445"

API Call: https://jsonmock.hackerrank.com/api/countries?name=Afghanistan


API Response (simplified):{"data":[{"name":"Afghanistan",
"callingCodes":["93"]}]}

Explanation: The calling code is "93". The formatted number is "+93 656445445".

Output: +93 656445445

Complete Code (Python)


Python
# ===================================================================
# The code below is typically pre-written by the platform (Boilerplate)
# ===================================================================
1 #!/bin/python3
2
3 import sys
4 import os
5 import requests # This import would be necessary
6 import json
7
8 #
9 # Complete the 'getPhoneNumbers' function below.
10 #
11 # The function is expected to return a STRING.
12 # The function accepts following parameters:
13 # 1. STRING country
14 # 2. STRING phoneNumber
15 # Base URL for copy/paste: https://jsonmock.hackerrank.com/api/countries?name=
16 #
17
18
# ===================================================================
# The code below is the solution you would write.
# ===================================================================
19 def getPhoneNumbers(country, phoneNumber):
20 base_url = "https://jsonmock.hackerrank.com/api/countries"
21 params = {'name': country}
22
23 try:
24 response = requests.get(base_url, params=params)
25 response.raise_for_status() # Raise an exception for bad status codes
26 data = response.json()
27
28 # Check if the data array is empty or does not exist
29 if not data['data']:
30 return "-1"
31
32 country_info = data['data'][0]
33 calling_codes = country_info.get('callingCodes', [])
34
35 # Check if calling codes list is empty
36 if not calling_codes:
37 return "-1"
38
39 # Use the calling code at the highest index
40 calling_code = calling_codes[-1]
41
42 return f"+{calling_code} {phoneNumber}"
43
44 except requests.exceptions.RequestException as e:
45 # Handle potential network errors
46 return "-1"
47
# ===================================================================
# The code below is also typically pre-written (Boilerplate)
# ===================================================================
48 if __name__ == '__main__':
49 # fptr = open(os.environ['OUTPUT_PATH'], 'w')
50
51 country = input()
52
53 phoneNumber = input()
54
55 result = getPhoneNumbers(country, phoneNumber)
56
57 print(result)
58
59 # fptr.write(result + '\n')
60 # fptr.close()

You might also like