0% found this document useful (0 votes)
60 views26 pages

Even EmpID Query

Uploaded by

aman.mehta2076
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)
60 views26 pages

Even EmpID Query

Uploaded by

aman.mehta2076
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/ 26

Even EmpID Query

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/26
write query

The SQL query to list the even `EmpID` values from the table `EMPLOYEEINFO` would be:

sql

SELECT EmpID
FROM EMPLOYEEINFO
WHERE EmpID % 2 = 0;

This query selects all `EmpID` values from the table `EMPLOYEEINFO` where the `EmpID` is an even
number (`EmpID % 2 = 0`).

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 2/26
write query

The SQL query to retrieve a list of employees, their corresponding department names, and their
respective managers (with "No Manager" displayed when there is no manager) would be:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 3/26
sql

SELECT e.emp_name AS employee_name,


d.department_name,
COALESCE(m.manager_name, 'No Manager') AS manager_name
FROM employees e
JOIN departments d ON e.department_id = d.dept_id
LEFT JOIN managers m ON e.manager_id = m.manager_id;

This query does the following:

Joins the `employees` table with the `departments` table to get the `department_name`.
Performs a left join on the `managers` table to get the `manager_name`.
Uses `COALESCE` to display "No Manager" if the `manager_id` is NULL.

write query

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 4/26
The SQL query to find the average age of customers whose email addresses end with ".com" and
display it along with the total number of such customers is:

sql

SELECT COUNT(*) AS NUM_CUSTOMERS,


AVG(AGE) AS AVG_AGE
FROM CUSTOMERS
WHERE EMAIL LIKE '%.com';

This query does the following:

`COUNT(*)`counts the total number of customers whose email ends with ".com".
`AVG(AGE)`calculates the average age of those customers.
The `WHERE` clause filters only the customers whose email addresses end with ".com".

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 5/26
write query

The SQL query to find the highest paid employee in each department is:

sql

SELECT d.DeptName,
e.EmpName,
s.Salary
FROM Employees e
JOIN Salaries s ON e.EmpID = s.EmpID
JOIN Departments d ON e.DeptID = d.DeptID
WHERE s.Salary = (

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 6/26
SELECT MAX(s2.Salary)
FROM Employees e2
JOIN Salaries s2 ON e2.EmpID = s2.EmpID
WHERE e2.DeptID = e.DeptID
);

This query:

Joins the `Employees`, `Salaries`, and `Departments` tables.


Uses a subquery to find the maximum salary in each department (`MAX(s2.Salary)`).
Displays the department name (`DeptName`), employee name (`EmpName`), and salary (`Salary`) for
the highest-paid employee in each department.

write query

The SQL query to find the top 5 departments with the highest average salary, along with the average
salary for each department (excluding departments with fewer than 5 employees), is:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 7/26
sql

SELECT e.department,
AVG(s.salary) AS average_salary
FROM Employees e
JOIN Salaries s ON e.emp_id = s.emp_id
GROUP BY e.department
HAVING COUNT(e.emp_id) >= 5
ORDER BY average_salary DESC
LIMIT 5;

This query:

Joins the `Employees` and `Salaries` tables.


Groups the results by `department` and calculates the average salary for each department using
`AVG(s.salary)`.
Filters out departments with fewer than 5 employees using the `HAVING COUNT(e.emp_id) >= 5`
condition.
Orders the results by the average salary in descending order (`ORDER BY average_salary DESC`)
and limits the output to the top 5 departments using `LIMIT 5`.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 8/26
write query

The SQL query to retrieve the unique `CustomerID` along with the total amount spent by each
customer, combining both orders and sales, is:

sql

SELECT CustomerID, SUM(Amount) AS TotalSpending


FROM (
SELECT CustomerID, Amount
FROM Orders
UNION ALL
SELECT CustomerID, Amount
FROM Sales

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 9/26
) AS Combined
GROUP BY CustomerID;

This query:

Combines the `Orders` and `Sales` tables using `UNION ALL` to include all records from both
tables.
Groups the results by `CustomerID` and calculates the total amount spent (`SUM(Amount)`) for each
customer.
The final output shows the `CustomerID` and the combined total spending.

write query

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 10/26
The SQL query to return the count of the total number of leads created in the months of April, May,
and June is:

sql

SELECT COUNT(*) AS Count


FROM Leads
WHERE Created_Date IN ('APRIL', 'MAY', 'JUNE');

This query:

Counts the number of records in the `Leads` table where the `Created_Date` is either 'APRIL',
'MAY', or 'JUNE'.
The result will give the count of leads for these specific months.

it is giving output 4, but it should be 2

The issue could be caused by case sensitivity or extra spaces in the `Created_Date` column. To address
this, you can normalize the case and trim any spaces around the values. Here's the corrected SQL
query:

sql

SELECT COUNT(*) AS Count


FROM Leads
WHERE TRIM(UPPER(Created_Date)) IN ('APRIL', 'MAY', 'JUNE');

This query:

Uses `UPPER()` to convert the `Created_Date` values to uppercase, ensuring case insensitivity.
Uses `TRIM()` to remove any leading or trailing spaces.
Then checks if the cleaned `Created_Date` is either 'APRIL', 'MAY', or 'JUNE', and counts the
matching records.

This should return the correct count.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 11/26
write c++ code

Here is the C++ code to solve the problem:

cpp

#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;

bool isPermutation(string s1, string s2) {


// If s1 is longer than s2, it's impossible to have a permutation of s1 in s2
if (s1.size() > s2.size()) {
return false;
}

// Create frequency maps for s1 and the first window of s2


unordered_map<char, int> s1_map, s2_map;
for (char c : s1) {
s1_map[c]++;
}

for (int i = 0; i < s1.size(); i++) {


s2_map[s2[i]]++;
}

// Check if the first window is a permutation


if (s1_map == s2_map) {
return true;
}

// Slide the window over s2


for (int i = s1.size(); i < s2.size(); i++) {
// Remove the left character of the previous window
s2_map[s2[i - s1.size()]]--;
if (s2_map[s2[i - s1.size()]] == 0) {
s2_map.erase(s2[i - s1.size()]);
}

// Add the right character of the current window


s2_map[s2[i]]++;

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 12/26
// Check if the current window is a permutation
if (s1_map == s2_map) {
return true;
}
}

return false;
}

int main() {
string s1, s2;
cout << "Enter string s1: ";
cin >> s1;
cout << "Enter string s2: ";
cin >> s2;

if (isPermutation(s1, s2)) {
cout << "check_string=True" << endl;
} else {
cout << "check_string=False" << endl;

Here is the JavaScript code to solve the problem:

javascript

function isPermutation(s1, s2) {


// If s1 is longer than s2, it's impossible to have a permutation of s1 in s2
if (s1.length > s2.length) {
return false;
}

// Helper function to compare two frequency maps


function compareMaps(map1, map2) {
if (map1.size !== map2.size) return false;
for (let [key, value] of map1) {
if (map2.get(key) !== value) {
return false;
}
}
return true;
}

// Create frequency maps for s1 and the first window of s2


let s1Map = new Map();
let s2Map = new Map();

for (let char of s1) {


s1Map.set(char, (s1Map.get(char) || 0) + 1);
}

for (let i = 0; i < s1.length; i++) {


s2Map.set(s2[i], (s2Map.get(s2[i]) || 0) + 1);
}

// Check if the first window is a permutation


if (compareMaps(s1Map, s2Map)) {
return true;
}

// Slide the window over s2


for (let i = s1.length; i < s2.length; i++) {
let leftChar = s2[i - s1.length];
let rightChar = s2[i];

// Remove the left character of the previous window


s2Map.set(leftChar, s2Map.get(leftChar) - 1);
if (s2Map.get(leftChar) === 0) {
s2Map.delete(leftChar);
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 13/26
// Add the right character of the current window
s2Map.set(rightChar, (s2Map.get(rightChar) || 0) + 1);

// Check if the current window is a permutation


if (compareMaps(s1Map, s2Map)) {
return true;
}
}

return false;
}

// Test the function


let s1 = "qwa";
let s2 = "wqawsdfgt";
let check_string = isPermutation(s1, s2);
console.log("check_string:", check_string);

Explanation:

The `isPermutation` function checks whether any permutation of string `s1` is a substring of
string `s2`.
It uses a sliding window approach with frequency maps to count the characters in each window
of `s2` and compare them with the character counts of `s1`.
A helper function `compareMaps` is used to compare the two maps (frequency maps of `s1` and
the current window in `s2`).
The function returns `true` if a permutation of `s1` is found in `s2`; otherwise, it returns `false`.

write javascript code

Here is the JavaScript code to solve the majority element problem:

javascript

function major_element(arr, n) {
// Create a map to store the frequency of elements
let freqMap = new Map();

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 14/26
// Iterate over the array and populate the frequency map
for (let i = 0; i < n; i++) {
freqMap.set(arr[i], (freqMap.get(arr[i]) || 0) + 1);
}

// Find the majority element


for (let [key, value] of freqMap) {
if (value > n / 2) {
return key; // Return the majority element
}
}

// If no majority element is found, return -1


return -1;
}

// Test case 1
let n1 = 10;
let arr1 = [6, 1, 6, 2, 6, 6, 5, 24, 6, 22];
console.log("maximum_times =", major_element(arr1, n1)); // Output: maximum_times = -1

// Test case 2
let n2 = 9;
let arr2 = [1, 2, 3, 3, 3, 3, 5, 6, 3];
console.log("maximum_times =", major_element(arr2, n2)); // Output: maximum_times = 3

Explanation:

1. The function `major_element` takes an array `arr` and its size `n` as inputs.
2. A frequency map (`freqMap`) is used to count how many times each element appears in the array.
3. After creating the frequency map, the code iterates through the map and checks if any element
appears more than `n / 2` times.
4. If such an element is found, it is returned as the majority element; otherwise, the function
returns `-1` if no majority element exists.

Test cases:

The first test case outputs `-1` because no element appears more than `n/2` times.
The second test case outputs `3` because `3` appears more than `n/2` times.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 15/26
javascript code

Here is the JavaScript code to solve the problem of finding the minimum number of runways required
at an airport:

javascript

function runways_required(arrival_time, departure_time, no_of_planes) {


// Sort the arrival and departure times
arrival_time.sort((a, b) => a - b);
departure_time.sort((a, b) => a - b);

let runways_needed = 1;
let max_runways = 1;

let i = 1; // pointer for arrival_time


let j = 0; // pointer for departure_time

// Traverse through the arrival and departure times


while (i < no_of_planes && j < no_of_planes) {
// If the next plane arrives before the current one departs, increase the count of
runways needed
if (arrival_time[i] <= departure_time[j]) {
runways_needed++;
i++;
}
// If the next plane departs before the next one arrives, decrease the count of
runways needed
else {
runways_needed--;
j++;
}

// Update the maximum number of runways needed at any time


max_runways = Math.max(max_runways, runways_needed);
}

return max_runways;
}

// Sample test cases


let arrival1 = [2200, 2300];
let departure1 = [0200, 0300];
let no_of_planes1 = 2;
console.log(runways_required(arrival1, departure1, no_of_planes1)); // Output: 2

let arrival2 = [900, 920, 950, 1000, 1100, 1800];


let departure2 = [930, 1200, 1120, 1130, 1900, 2000];
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 16/26
let no_of_planes2 = 6;
console.log(runways_required(arrival2, departure2, no_of_planes2)); // Output: 4

Explanation:

1. Sorting: The `arrival_time` and `departure_time` arrays are sorted to handle the time events
sequentially.
2. Two pointers: Two pointers (`i` for arrival times and `j` for departure times) are used to
traverse both arrays.
3. Runway count: Each time a plane arrives before another departs, the number of runways
needed increases. When a plane departs, the number of runways needed decreases.
4. Max runways: The maximum number of runways required at any point in time is tracked and
returned as the result.

This approach ensures that the runways required are calculated based on overlapping flight times.

the first test case output should be 2, but it is coming 1

The issue arises because the departure times provided are in the 24-hour format (e.g., 0200 for 2:00
AM). Since JavaScript treats leading zeroes as octal numbers, this causes incorrect comparisons. To
avoid this, you should treat times as integers without leading zeroes or use proper 24-hour time
conversion for comparison.

Here’s the corrected JavaScript code:

javascript

function runways_required(arrival_time, departure_time, no_of_planes) {


// Sort the arrival and departure times
arrival_time.sort((a, b) => a - b);
departure_time.sort((a, b) => a - b);

let runways_needed = 1;
let max_runways = 1;

let i = 1; // pointer for arrival_time


let j = 0; // pointer for departure_time

// Traverse through the arrival and departure times


while (i < no_of_planes && j < no_of_planes) {
// If the next plane arrives before the current one departs, increase the count of
runways needed
if (arrival_time[i] < departure_time[j]) {
runways_needed++;
i++;
}
// If the next plane departs before the next one arrives, decrease the count of
runways needed
else {
runways_needed--;
j++;
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 17/26
// Update the maximum number of runways needed at any time
max_runways = Math.max(max_runways, runways_needed);
}

return max_runways;
}

// Sample test cases


let arrival1 = [2200, 2300];
let departure1 = [200, 300]; // Use integers without leading zeroes for departure times
let no_of_planes1 = 2;
console.log(runways_required(arrival1, departure1, no_of_planes1)); // Output: 2

let arrival2 = [900, 920, 950, 1000, 1100, 1800];


let departure2 = [930, 1200, 1120, 1130, 1900, 2000];
let no_of_planes2 = 6;
console.log(runways_required(arrival2, departure2, no_of_planes2)); // Output: 4

Explanation of the Fix:

I removed the leading zero from the departure times like `0200`, which was causing issues due to
JavaScript treating those numbers as octal.
Now the departure times are treated as normal integers (`200` for 2:00 AM instead of `0200`).

Now, the first test case should correctly output `2` as expected.

sort the arival time and departure time pairs in ascending order of departure time, and then
calculate the number of overlappimg intervals, that will be the answer

Thanks for the clarification! To solve the problem by sorting the `arrival_time` and `departure_time`
pairs in ascending order of departure time and calculating the number of overlapping intervals
(runways required), here's the updated approach:

Plan:

1. Pair the arrival and departure times.


2. Sort the pairs by departure time.
3. Iterate through the sorted times to count the maximum overlapping intervals.

Here’s the updated JavaScript code based on your request:

javascript

function runways_required(arrival_time, departure_time, no_of_planes) {


// Create pairs of arrival and departure times
let time_pairs = [];
for (let i = 0; i < no_of_planes; i++) {
time_pairs.push([arrival_time[i], departure_time[i]]);
}

// Sort the time pairs by departure time (second value of the pair)
time_pairs.sort((a, b) => a[1] - b[1]);

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 18/26
let runways_needed = 0;
let max_runways = 0;

// Track the list of planes currently using the runways


let active_flights = [];

for (let i = 0; i < no_of_planes; i++) {


let current_arrival = time_pairs[i][0];
let current_departure = time_pairs[i][1];

// Remove flights that have already departed


active_flights = active_flights.filter(departure => departure > current_arrival);

// Add the current flight's departure time to the active flights


active_flights.push(current_departure);

// Update the maximum number of runways required


max_runways = Math.max(max_runways, active_flights.length);
}

return max_runways;
}

// Sample test cases


let arrival1 = [2200, 2300];
let departure1 = [200, 300]; // Adjust the departure times without leading zeroes
let no_of_planes1 = 2;
console.log(runways_required(arrival1, departure1, no_of_planes1)); // Output: 2

let arrival2 = [900, 920, 950, 1000, 1100, 1800];


let departure2 = [930, 1200, 1120, 1130, 1900, 2000];
let no_of_planes2 = 6;
console.log(runways_required(arrival2, departure2, no_of_planes2)); // Output: 4

Explanation:

1. Pairing and Sorting:


We pair each arrival and departure time (`time_pairs[i] = [arrival_time[i],
departure_time[i]]`).
Then we sort the pairs by their departure times (`time_pairs.sort((a, b) => a[1] - b[1])`).
2. Counting Overlapping Intervals:
We maintain an array `active_flights` that holds the departure times of planes currently
on the runway.
For each plane, we remove planes from `active_flights` whose departure times are earlier
than the current plane's arrival (as they have already departed).
Then, we add the current plane's departure time and update the maximum number of
runways required.

By sorting the planes by departure times and checking overlapping intervals, the code correctly
calculates the minimum number of runways required at any time.

class Solution{
public:
//Function to find the minimum number of platforms required at the
//railway station such that no train waits.
int findPlatform(int arr[], int dep[], int n)
{
sort(arr, arr+n);
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 19/26
sort(dep, dep+n);

int i=0;
int j=0;

int count = 0;
int ans = 0;

while (i<n) {
if (arr[i]<=dep[j]) {
count++;
ans = max(count, ans);
i++;
}
else {
count--;
j++;
}
}

return ans;
}
};

convert this into js

Here is the JavaScript equivalent of the C++ code you provided:

javascript

function findPlatform(arr, dep, n) {


// Sort the arrival and departure times
arr.sort((a, b) => a - b);
dep.sort((a, b) => a - b);

let i = 0; // Pointer for arrival times


let j = 0; // Pointer for departure times

let count = 0; // To keep track of platforms currently in use


let ans = 0; // To store the minimum number of platforms required

// Traverse through all trains


while (i < n) {
if (arr[i] <= dep[j]) {
count++; // A new train arrives, increase the platform count
ans = Math.max(count, ans); // Update the maximum platform count if needed
i++;
} else {
count--; // A train departs, reduce the platform count
j++;
}
}

return ans; // Return the minimum number of platforms required


}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 20/26
// Sample test case
let arr = [900, 940, 950, 1100, 1500, 1800];
let dep = [910, 1200, 1120, 1130, 1900, 2000];
let n = arr.length;

console.log(findPlatform(arr, dep, n)); // Output: 3

Explanation:

1. Sorting: The arrival and departure arrays are sorted to process trains in a chronological
sequence.
2. Two Pointers: `i` and `j` are used to traverse the `arr` and `dep` arrays respectively.
If a train arrives before or at the same time another train departs, a new platform is needed
(`count++`).
If a train departs before another arrives, a platform becomes free (`count--`).
3. Max Platforms: The variable `ans` stores the maximum number of platforms required at any
time by updating it when more platforms are in use than before.

Sample Test Case:

For the input `arr = [900, 940, 950, 1100, 1500, 1800]` and `dep = [910, 1200, 1120, 1130,
1900, 2000]`, the function correctly calculates that 3 platforms are required at the busiest time.

it is not working for this input


let arr = [2200, 2300];
let dep = [200, 300];

The issue arises because the times are given in 24-hour format, and times like `0200` (or `200` without
the leading zero) represent times that are technically on the next day, but your logic is treating them
as smaller than the arrival times like `2200` and `2300` on the same day.

To handle this, we need to adjust the departure times that are smaller than the arrival times, as they
occur the next day. For example, a departure time of `200` should be treated as `2600` to indicate that
it's on the next day.

Here’s the corrected JavaScript code:

javascript

function findPlatform(arr, dep, n) {


// Adjust for the departure times that are on the next day
for (let i = 0; i < n; i++) {
if (dep[i] < arr[i]) {
dep[i] += 2400; // Add 2400 to account for the next day
}
}

// Sort the arrival and adjusted departure times


arr.sort((a, b) => a - b);

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 21/26
dep.sort((a, b) => a - b);

let i = 0; // Pointer for arrival times


let j = 0; // Pointer for departure times

let count = 0; // To keep track of platforms currently in use


let ans = 0; // To store the minimum number of platforms required

// Traverse through all trains


while (i < n) {
if (arr[i] <= dep[j]) {
count++; // A new train arrives, increase the platform count
ans = Math.max(count, ans); // Update the maximum platform count if needed
i++;
} else {
count--; // A train departs, reduce the platform count
j++;
}
}

return ans; // Return the minimum number of platforms required


}

// Test case with times crossing midnight


let arr = [2200, 2300];
let dep = [200, 300];
let n = arr.length;

console.log(findPlatform(arr, dep, n)); // Output: 2

Explanation:

Adjusting Departure Times: We adjust the departure times that happen after midnight by
adding `2400` to them. This allows us to correctly compare the arrival times on the current day
with departure times that are technically on the next day.
For example, `0200` becomes `2600` and `0300` becomes `2700`.
Sorting: We then sort the adjusted departure times along with the arrival times.
Logic: The rest of the logic remains the same — we compare the arrival and departure times
using two pointers to track the number of platforms required.

Test Case:

For the input `arr = [2200, 2300]` and `dep = [200, 300]`, the function now correctly outputs
`2`, as two platforms are needed.

it is not working

Thank you for the clarification. To properly handle times that cross midnight (for example, an arrival
time of 22:00 with a departure time of 02:00 the next day), we need to handle the departure times by
correctly identifying which events happen on the next day without misinterpreting them.

Here’s the final, corrected approach for handling this:

Plan:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 22/26
Arrival and Departure Times: The departure times that are less than the arrival times (i.e., early
morning departures) should be considered as being on the next day.
Sorting: Sort both `arrival` and `departure` arrays.
Counting Overlaps: Use two pointers to count the overlapping intervals to calculate the number
of platforms required.

Here’s the updated JavaScript code:

javascript

function findPlatform(arr, dep, n) {


// Handle crossing over midnight by adjusting departure times that are less than their
corresponding arrival times
for (let i = 0; i < n; i++) {
if (dep[i] < arr[i]) {
dep[i] += 2400; // Add 2400 to indicate the next day
}
}

// Sort the arrival and departure times


arr.sort((a, b) => a - b);
dep.sort((a, b) => a - b);

let i = 0; // Pointer for arrival times


let j = 0; // Pointer for departure times

let count = 0; // To track platforms currently needed


let maxPlatforms = 0; // To store the maximum number of platforms required

// Traverse through all trains


while (i < n && j < n) {
if (arr[i] < dep[j]) {
// A new train arrives before the previous one departs
count++;
maxPlatforms = Math.max(maxPlatforms, count); // Update the maximum platform
count
i++; // Move to the next arrival
} else {
// A train departs, so one platform is freed
count--;
j++; // Move to the next departure
}
}

return maxPlatforms; // Return the minimum number of platforms required


}

// Test case with times crossing midnight


let arr = [2200, 2300];
let dep = [200, 300]; // Example where the departure happens the next day
let n = arr.length;

console.log(findPlatform(arr, dep, n)); // Output: 2

Explanation:

1. Midnight Crossings: For each train, if the departure time is earlier than the arrival time
(meaning the train departs after midnight), we adjust the departure time by adding 2400. This
effectively handles the next-day departures.
2. Sorting: We then sort both the arrival and departure arrays.
3. Counting Platforms: Using two pointers (`i` for arrivals and `j` for departures), we count how
many platforms are needed. Each time a train arrives before another departs, we increase the
count. Each time a train departs, we reduce the count.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 23/26
4. Result: The maximum value of `count` during the process gives the number of platforms
required.

Test Case:

For the input `arr = [2200, 2300]` and `dep = [200, 300]`, the function now correctly outputs
`2`, as two platforms are required because the second train arrives before the first one departs.

bool isPossible(vector<int>& arr, int n, int m, int pages) {


int count=1;
int sum=0;
for (int i=0; i<n; i++) {
sum+=arr[i];
if (sum>pages) {
count++;
sum=arr[i];
}
}

if (count<=m) return true;


return false;
}

int findPages(vector<int>& arr, int n, int m) {


int sum = 0;
int maxi = INT_MIN;

if (m>n) return -1;

for (int i=0; i<n; i++) {


sum+=arr[i];
maxi = max(arr[i], maxi);
}

int low = maxi;


int high = sum;

while (low<=high) {
int mid = low + (high-low)/2;
if (isPossible(arr, n, m, mid)) high = mid-1;
else low = mid+1;
}

return low;
}

--> WRITE IN JS

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 24/26
Here's the JavaScript version of the provided C++ code:

javascript

function isPossible(arr, n, m, pages) {


let count = 1;
let sum = 0;

for (let i = 0; i < n; i++) {


sum += arr[i];

if (sum > pages) {


count++;
sum = arr[i];
}
}

return count <= m;


}

function findPages(arr, n, m) {
let sum = 0;
let maxi = Number.MIN_SAFE_INTEGER;

// If the number of students is greater than the number of books, return -1


if (m > n) return -1;

// Calculate the total number of pages (sum) and the maximum number of pages in a
single book
for (let i = 0; i < n; i++) {
sum += arr[i];
maxi = Math.max(arr[i], maxi);
}

let low = maxi;


let high = sum;

// Perform binary search to find the minimum possible value


while (low <= high) {
let mid = Math.floor(low + (high - low) / 2);

if (isPossible(arr, n, m, mid)) {
high = mid - 1;
} else {
low = mid + 1;
}
}

return low;
}

// Example usage:
let arr = [12, 34, 67, 90];
let n = arr.length; // Number of books
let m = 2; // Number of students

console.log(findPages(arr, n, m)); // Output: 113

Explanation:

1. isPossible Function:
The `isPossible` function checks if it's possible to allocate the books such that the
maximum number of pages allocated to any student is less than or equal to `pages`.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 25/26
If the current sum of pages exceeds `pages`, we increment the student count (`count`) and
reset the sum to the current book's pages. This simulates giving the next student the
remaining books.
If the number of students required (`count`) is less than or equal to the given number of
students (`m`), it returns `true`.

2. findPages Function:
This function performs a binary search to find the minimum possible number of pages that
can be allocated to a student such that no student gets more than `pages` pages.
We calculate the sum of all pages (`sum`) and the maximum pages in any single book
(`maxi`).
The binary search is performed between the maximum pages in a single book (`low =
maxi`) and the total pages (`high = sum`). The goal is to find the minimum `low` where the
allocation is possible.

Example:

For the array `arr = [12, 34, 67, 90]` and `m = 2` students:

The output is `113`, meaning the minimum number of pages a student has to read to ensure no
student reads more than that is 113.
ChatGPT can make mistakes. Check important info.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 26/26

You might also like