All Three Dsa Questions PhonePe
All Three Dsa Questions PhonePe
import java.util.*;
int k = in.nextInt();
int n = in.nextInt();
if (n > 0) {
Arrays.sort(salaries);
}
int maxCount = 0;
int maxLevel = 1;
if (maxCount >= 1) {
System.out.println(maxLevel);
} else {
System.out.println(1);
}
}
This code is designed to solve the problem of determining the salary level with the highest
number of employees based on given salary ranges and employee salaries. Let's break the
explanation into parts.
Code Explanation
Input Parsing
Read the number of levels (kkk) and employees (nnn):
java
Copy code
int k = in.nextInt();
int n = in.nextInt();
1.
○ kkk specifies the number of salary levels.
○ nnn specifies the number of employees.
2.
3.
4.
○ Sorting helps efficiently find the range of salaries within [A[i],B[i]][A[i],
B[i]][A[i],B[i]] using binary search.
Processing Each Level
Initialize variables to track the level with the highest number of employees:
java
Copy code
int maxCount = 0; // Maximum employees in any level
int maxLevel = 1; // Index of the level with max employees
5.
For each level, calculate how many employees fall within the salary range:
java
Copy code
for (int i = 0; i < k; i++) {
int Ai = levels[i][0]; // Minimum salary for level i
int Bi = levels[i][1]; // Maximum salary for level i
6.
○ Binary Search:
■ lowerBound: Finds the first salary greater than or equal to A[i]A[i]A[i].
■ upperBound: Finds the first salary strictly greater than B[i]B[i]B[i].
■ The count of employees in the range is upper−lower\text{upper} -
\text{lower}upper−lower.
7.
○ Finds the index of the smallest element ≥\geq≥ key.
Upper Bound:
java
Copy code
private static int upperBound(int[] arr, int key) {
int low = 0, high = arr.length;
while (low < high) {
int mid = (low + high) / 2;
if (arr[mid] <= key) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
8.
○ Finds the index of the smallest element >>> key.
Output
If the maximum count of employees in any level is at least 1, print the level index:
java
Copy code
if (maxCount >= 1) {
System.out.println(maxLevel);
} else {
System.out.println(1);
}
9.
Algorithm
1. Input Reading:
○ Parse k,nk, nk,n (number of levels and employees).
○ Read salary ranges A[i],B[i]A[i], B[i]A[i],B[i] for kkk levels.
○ Read salaries of nnn employees.
2. Sorting:
○ Sort the employee salaries to enable binary search.
3. Iterate Through Levels:
○ For each level iii, calculate:
■ Lower Bound: Index of the first employee with salary ≥A[i]\geq A[i]≥A[i].
■ Upper Bound: Index of the first employee with salary >B[i]> B[i]>B[i].
■ Employee count for level iii = upper−lower\text{upper} -
\text{lower}upper−lower.
4. Track Maximum Count:
○ If the current level has more employees than the previous maximum, update:
■ maxCount = number of employees in this level.
■ maxLevel = current level index.
5. Output:
○ Print the 1-based index of the level with the most employees.
○ If no employees belong to any level, output 1.
Time Complexity
Space Complexity
Input:
Copy code
3 5
1 5
5 12
9 12
3
6
10
11
12
Execution:
Output:
Copy code
2
Q3
class Result {
return maxGroup;
}
if (totalOperations <= t) {
return true;
}
}
return false;
}
}
The provided solution uses binary search and prefix sums to efficiently solve the problem of
finding the largest group of candidates with equal votes after performing at most ttt
manipulations. Here's a step-by-step explanation of the approach using an example:
Example Input:
Step-by-Step Solution:
The first step is to sort the candidates' votes in ascending order to simplify calculations.
The prefix sum helps us quickly calculate the total votes for any subarray.
Prefix sums:
● Prefix[0] = 6
● Prefix[1] = 6+7=136 + 7 = 136+7=13
● Prefix[2] = 13+9=2213 + 9 = 2213+9=22
● Prefix[3] = 22+11=3322 + 11 = 3322+11=33
For each group size kkk, we check if it's possible to make kkk consecutive votes equal using at
most ttt manipulations.
● Calculating the total operations required to make the group equal using the median vote
(minimizing manipulations).
● Checking if the total operations are less than or equal to ttt.
● Possible groups:
1. [6,7][6, 7][6,7]: Operations to make votes equal to 7:
(7−6)=1(7 - 6) = 1(7−6)=1 → Total = 1 (fits within t=3t = 3t=3).
2. [7,9][7, 9][7,9]: Operations to make votes equal to 9:
(9−7)=2(9 - 7) = 2(9−7)=2 → Total = 2 (fits within t=3t = 3t=3).
3. [9,11][9, 11][9,11]: Operations to make votes equal to 11:
(11−9)=2(11 - 9) = 2(11−9)=2 → Total = 2 (fits within t=3t = 3t=3).
● Possible groups:
1. [6,7,9][6, 7, 9][6,7,9]: Operations to make votes equal to 7 (median):
(7−6)+(9−7)=1+2=3(7 - 6) + (9 - 7) = 1 + 2 = 3(7−6)+(9−7)=1+2=3 → Total = 3
(fits within t=3t = 3t=3).
2. [7,9,11][7, 9, 11][7,9,11]: Operations to make votes equal to 9 (median):
(9−7)+(11−9)=2+2=4(9 - 7) + (11 - 9) = 2 + 2 = 4(9−7)+(11−9)=2+2=4 → Total = 4
(exceeds t=3t = 3t=3).
Thus, k=3k = 3k=3 is feasible for the first group but not the second.
6. Result:
1. Binary Search:
○ Used to efficiently find the maximum kkk (group size).
2. Prefix Sum:
○ Helps compute the total number of operations for any group in O(1)O(1)O(1)
time.
3. Median Vote:
○ Minimizing the manipulations by making all votes in a group equal to the median.
Complexity:
Code Overview
The goal of the code is to determine the largest group of candidates that can have the same
number of votes after performing at most ttt manipulations. The solution uses binary search to
find the maximum group size and leverages prefix sums for efficient calculations.
Code Components
java
Copy code
Collections.sort(candidates); // Step 1: Sort the votes.
Here, low\text{low}low and high\text{high}high represent the search range for the group size
kkk. The binary search loop is as follows:
java
Copy code
while (low <= high) {
int mid = low + (high - low) / 2; // Middle of the range.
if (isPossible(candidates, prefix, mid, t)) {
maxGroup = mid; // If group size mid is feasible, update
maxGroup.
low = mid + 1; // Try larger group sizes.
} else {
high = mid - 1; // Reduce group size.
}
}
● The binary search checks group sizes from 111 to nnn.
● If a group size kkk is possible, it updates maxGroup and looks for larger sizes.
● Otherwise, it reduces the search range.
Finally, the function returns the largest feasible group size (maxGroup).
This function precomputes prefix sums of the sorted votes array for quick range-sum queries.
java
Copy code
private static List<Long> computePrefixSums(List<Integer> votes) {
int n = votes.size();
List<Long> prefix = new ArrayList<>(Collections.nCopies(n, 0L));
prefix.set(0, (long) votes.get(0)); // First element is itself.
for (int i = 1; i < n; i++) {
prefix.set(i, prefix.get(i - 1) + votes.get(i)); // Cumulative
sum.
}
return prefix;
}
● Prefix sum at index iii is the sum of all votes from index 000 to iii.
● Time complexity: O(n)O(n)O(n).
This function determines whether a group of size kkk can be made to have equal votes using at
most ttt manipulations.
How it works:
● Iterate over all possible groups of size kkk in the sorted array.
● For each group:
○ Calculate the median of the group, which minimizes the total manipulations.
○ Compute the number of operations needed to make all votes equal to the
median.
○ Check if the operations required are ≤t\leq t≤t.
java
Copy code
for (int i = 0; i + k - 1 < n; i++) {
int left = i;
int right = i + k - 1;
int medianPos = left + (k - 1) / 2;
Here, left and right represent the start and end indices of the group, while medianPos is
the position of the median.
Calculating Manipulations:
Left Side Manipulations: To bring votes from left to medianPos up to the median:
java
Copy code
long leftSum = median * (medianPos - left + 1)
- (prefix.get(medianPos) - (left > 0 ? prefix.get(left -
1) : 0));
1.
○ median * (medianPos - left + 1): Total votes needed to make this
range equal to the median.
○ prefix.get(medianPos): Total sum of votes from left to medianPos.
○ Subtracting these gives the operations needed to adjust the left side.
Right Side Manipulations: To bring votes from medianPos + 1 to right down to the
median:
java
Copy code
long rightSum = (prefix.get(right) - prefix.get(medianPos))
- median * (right - medianPos);
2.
○ prefix.get(right) - prefix.get(medianPos): Total sum of votes from
medianPos + 1 to right.
○ median * (right - medianPos): Total votes needed to make this range
equal to the median.
○ Subtracting these gives the operations needed to adjust the right side.
Total Operations:
java
Copy code
long totalOperations = leftSum + rightSum;
3.
4. Feasibility Check: If totalOperations <= t, then this group is feasible.
java
Copy code
if (totalOperations <= t) {
return true;
}
The binary search finds the largest kkk for which isPossible() returns true, and that is
returned as the result.
Complexity Analysis
Since binary search runs for logn\log nlogn iterations, and each feasibility check is
O(n)O(n)O(n), the total complexity is:
Summary of Steps
Q1
import java.util.*;
if (N == 0) {
System.out.println(0);
return;
}
queue.add(N);
visited.add(N);
int moves = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
long current = queue.poll();
if (current == 0) {
System.out.println(moves);
return;
}
System.out.println(-1);
}
This code is solving a problem where the goal is to find the minimum number of operations
required to reduce a number NNN to 0. The allowed operations are:
1. Input Handling
java
Copy code
Scanner in = new Scanner(System.in);
long N = in.nextLong();
in.close();
2. Base Case
java
Copy code
if (N == 0) {
System.out.println(0);
return;
}
● queue: Used for BFS (Breadth-First Search) to explore all possible states of NNN.
● visited: Tracks already visited numbers to avoid revisiting them.
4. Starting BFS
java
Copy code
queue.add(N);
visited.add(N);
int moves = 0;
● The initial state (number NNN) is added to the queue and marked as visited.
● A counter moves is initialized to track the number of operations performed.
The BFS algorithm explores all possible states of NNN level by level:
java
Copy code
while (!queue.isEmpty()) {
int size = queue.size(); // Number of elements at the current
level.
for (int i = 0; i < size; i++) {
long current = queue.poll();
● If the current number becomes 000, print the number of moves and terminate.
● Subtract 1 Operation:
java
Copy code
if (current - 1 >= 0 && !visited.contains(current - 1)) {
queue.add(current - 1);
visited.add(current - 1);
}
● Checks if subtracting 1 is valid and adds the result to the queue if not already visited.
● Replace with Larger Divisor:
java
Copy code
for (long state : getNextStates(current)) {
if (!visited.contains(state)) {
queue.add(state);
visited.add(state);
}
}
● Calls the helper method getNextStates to generate possible larger divisors and adds
them to the queue.
● After processing all numbers at the current level, increment the moves counter.
If no solution is found (shouldn't happen for valid input), the algorithm will print -1 at the end.
getNextStates Method
This method generates all possible "next states" by finding divisors of NNN:
java
Copy code
private static List<Long> getNextStates(long N) {
List<Long> states = new ArrayList<>();
for (long a = 1; a * a <= N; a++) {
if (N % a == 0) { // a is a divisor
long b = N / a; // paired divisor
long nextState = Math.max(a, b);
if (nextState < N) { // Only consider states less than N
states.add(nextState);
}
}
}
return states;
}
Algorithm
1. Initialize BFS:
○ Add NNN to a queue and mark it as visited.
○ Initialize a counter moves to 0.
2. Perform BFS:
○ While the queue is not empty:
■ For each number at the current level:
■ If the number is 000, print moves and exit.
■ Add N−1N-1N−1 to the queue if not visited.
■ Generate all divisors of NNN and add the larger divisor to the
queue if not visited.
■ Increment moves.
3. Generate Divisors:
○ For each divisor pair a,ba, ba,b of NNN, add the larger value max(a,b)\max(a,
b)max(a,b) to the next states.
4. Output:
○ If NNN is reduced to 000, print the number of moves.
○ If no solution exists, print -1.