0% found this document useful (0 votes)
13 views21 pages

All Three Dsa Questions PhonePe

g
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)
13 views21 pages

All Three Dsa Questions PhonePe

g
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/ 21

Q2

import java.util.*;

public class Source {


public static void main(String[] args) {
Scanner in = new Scanner(System.in);

int k = in.nextInt();
int n = in.nextInt();

int[][] levels = new int[k][2];


for (int i = 0; i < k; i++) {
levels[i][0] = in.nextInt();
levels[i][1] = in.nextInt();
}

int[] salaries = new int[n];


for (int i = 0; i < n; i++) {
salaries[i] = in.nextInt();
}

if (n > 0) {
Arrays.sort(salaries);
}

int maxCount = 0;
int maxLevel = 1;

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


int Ai = levels[i][0];
int Bi = levels[i][1];

int lower = lowerBound(salaries, Ai);


int upper = upperBound(salaries, Bi);
int count = upper - lower;

if (count > maxCount) {


maxCount = count;
maxLevel = i + 1;
}
}

if (maxCount >= 1) {
System.out.println(maxLevel);
} else {
System.out.println(1);
}
}

private static int lowerBound(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;
}

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;
}
}

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.

Read the salary ranges (A[i],B[i]A[i], B[i]A[i],B[i]) for each level:


java
Copy code
int[][] levels = new int[k][2];
for (int i = 0; i < k; i++) {
levels[i][0] = in.nextInt(); // Minimum salary A[i]
levels[i][1] = in.nextInt(); // Maximum salary B[i]
}

2.

Read the salaries of all employees:


java
Copy code
int[] salaries = new int[n];
for (int i = 0; i < n; i++) {
salaries[i] = in.nextInt();
}

3.

Sort the salaries:


java
Copy code
if (n > 0) {
Arrays.sort(salaries);
}

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

int lower = lowerBound(salaries, Ai);


int upper = upperBound(salaries, Bi);
int count = upper - lower;

if (count > maxCount) {


maxCount = count;
maxLevel = i + 1; // Update to the current level (1-based
index)
}
}

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.

Binary Search Utility Functions


Lower Bound:
java
Copy code
private static int lowerBound(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;
}

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

1. Sorting Salaries: O(nlog⁡n)O(n \log n)O(nlogn)


2. Binary Search for Each Level: O(klog⁡n)O(k \log n)O(klogn)
3. Overall: O(nlog⁡n+klog⁡n)O(n \log n + k \log n)O(nlogn+klogn)

Space Complexity

● O(n+k)O(n + k)O(n+k) for storing salaries and levels.


Example

Input:
Copy code
3 5
1 5
5 12
9 12
3
6
10
11
12

Execution:

1. Sorted Salaries: [3, 6, 10, 11, 12].


2. Level 1: Count = 1.
3. Level 2: Count = 4.
4. Level 3: Count = 3.
5. Max Count = 4 → Level 2.

Output:
Copy code
2

Q3

class Result {

public static int maxCandidatesWithEqualVoteCount(List<Integer> candidates, long t) {


Collections.sort(candidates);
List<Long> prefix = computePrefixSums(candidates);

int low = 1, high = candidates.size(), maxGroup = 1;

while (low <= high) {


int mid = low + (high - low) / 2;
if (isPossible(candidates, prefix, mid, t)) {
maxGroup = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}

return maxGroup;
}

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));
for (int i = 1; i < n; i++) {
prefix.set(i, prefix.get(i - 1) + votes.get(i));
}
return prefix;
}

private static boolean isPossible(List<Integer> votes, List<Long> prefix, int k, long t) {


int n = votes.size();
for (int i = 0; i + k - 1 < n; i++) {
int left = i;
int right = i + k - 1;
int medianPos = left + (k - 1) / 2;

long median = votes.get(medianPos);


long leftSum = median * (medianPos - left + 1) - (prefix.get(medianPos) - (left > 0 ?
prefix.get(left - 1) : 0));
long rightSum = (prefix.get(right) - prefix.get(medianPos)) - median * (right -
medianPos);

long totalOperations = leftSum + rightSum;

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:

Candidates' votes: [6,7,11,9][6, 7, 11, 9][6,7,11,9]


Allowed manipulations (ttt): 333

Step-by-Step Solution:

1. Sort the Candidates:

The first step is to sort the candidates' votes in ascending order to simplify calculations.

Sorted votes: [6,7,9,11][6, 7, 9, 11][6,7,9,11]

2. Compute Prefix Sums:

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

So, Prefix array: [6,13,22,33][6, 13, 22, 33][6,13,22,33]

3. Binary Search for Maximum Group Size:


We use binary search to determine the largest group size kkk such that ttt manipulations are
enough to make all votes in the group equal.

● Initial Range: low=1,high=n=4low = 1, high = n = 4low=1,high=n=4 (where nnn is the


number of candidates).

4. Check Feasibility for Group Size kkk:

For each group size kkk, we check if it's possible to make kkk consecutive votes equal using at
most ttt manipulations.

The helper function isPossible() does this by:

● 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.

5. Iterate Through Binary Search:

For k=1k = 1k=1 to 444, here's how the process unfolds:

Case: k=2k = 2k=2

● 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).

Thus, k=2k = 2k=2 is feasible.

Case: k=3k = 3k=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.

Case: k=4k = 4k=4

● Possible group: [6,7,9,11][6, 7, 9, 11][6,7,9,11].


● Operations to make votes equal to 9 (median):
(9−6)+(9−7)+(11−9)=3+2+2=7(9 - 6) + (9 - 7) + (11 - 9) = 3 + 2 + 2 =
7(9−6)+(9−7)+(11−9)=3+2+2=7 → Total = 7 (exceeds t=3t = 3t=3).

Thus, k=4k = 4k=4 is not feasible.

6. Result:

The largest feasible group size is k=3k = 3k=3.

Key Points in the Code:

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:

● Sorting: O(nlog⁡n)O(n \log n)O(nlogn)


● Binary Search: O(log⁡n)O(\log n)O(logn)
● Checking Feasibility for Each kkk: O(n)O(n)O(n)

Overall: O(nlog⁡n)O(n \log n)O(nlogn)

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

1. Main Function: maxCandidatesWithEqualVoteCount

This is the main function that:

1. Sorts the votes to simplify group selection.


2. Computes prefix sums of the votes.
3. Uses binary search to find the largest group size kkk such that all members of the group
can have equal votes within ttt manipulations.

java
Copy code
Collections.sort(candidates); // Step 1: Sort the votes.

List<Long> prefix = computePrefixSums(candidates); // Step 2: Compute


prefix sums.

int low = 1, high = candidates.size(), maxGroup = 1;

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).

2. Helper Function: computePrefixSums

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).

3. Feasibility Check: isPossible

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;

long median = votes.get(medianPos); // Median vote in the group.

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;
}

4. Return the Largest Feasible Group Size

The binary search finds the largest kkk for which isPossible() returns true, and that is
returned as the result.

Complexity Analysis

1. Sorting: O(nlog⁡n)O(n \log n)O(nlogn)


2. Prefix Sum Calculation: O(n)O(n)O(n)
3. Binary Search: O(log⁡n)O(\log n)O(logn)
4. Feasibility Check per kkk: O(n)O(n)O(n)

Since binary search runs for log⁡n\log nlogn iterations, and each feasibility check is
O(n)O(n)O(n), the total complexity is:

O(nlog⁡n)O(n \log n)O(nlogn)

Summary of Steps

1. Sort the votes to simplify group analysis.


2. Compute prefix sums for efficient range-sum queries.
3. Use binary search to find the maximum group size kkk.
4. For each kkk, use the median to calculate the minimum manipulations required for
feasibility.
5. Return the largest feasible group size.
Example Walkthrough:

For votes=[6,7,11,9]\text{votes} = [6, 7, 11, 9]votes=[6,7,11,9] and t=3t = 3t=3:

● Sorting: [6,7,9,11][6, 7, 9, 11][6,7,9,11].


● Prefix sums: [6,13,22,33][6, 13, 22, 33][6,13,22,33].
● Binary search checks:
○ k=2k = 2k=2: Feasible.
○ k=3k = 3k=3: Feasible.
○ k=4k = 4k=4: Not feasible.
● Result: 333.

Q1

import java.util.*;

public class Source {


public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long N = in.nextLong();
in.close();

if (N == 0) {
System.out.println(0);
return;
}

Queue<Long> queue = new LinkedList<>();


Set<Long> visited = new HashSet<>();

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;
}

if (current - 1 >= 0 && !visited.contains(current - 1)) {


queue.add(current - 1);
visited.add(current - 1);
}

for (long state : getNextStates(current)) {


if (!visited.contains(state)) {
queue.add(state);
visited.add(state);
}
}
}
moves++;
}

System.out.println(-1);
}

private static List<Long> getNextStates(long N) {


List<Long> states = new ArrayList<>();
for (long a = 1; a * a <= N; a++) {
if (N % a == 0) {
long b = N / a;
long nextState = Math.max(a, b);
if (nextState < N) {
states.add(nextState);
}
}
}
return states;
}
}

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. Subtract 1 from NNN.


2. Replace NNN with the larger of its two divisors (a,b)(a, b)(a,b), where a×b=Na \times b =
Na×b=N and a≤ba \leq ba≤b.
Step-by-Step Explanation

1. Input Handling
java
Copy code
Scanner in = new Scanner(System.in);
long N = in.nextLong();
in.close();

● Reads a long integer NNN as input.


● Closes the scanner to release resources.

2. Base Case
java
Copy code
if (N == 0) {
System.out.println(0);
return;
}

● If N=0N = 0N=0, it directly prints 0 since no operations are needed.

3. Data Structures Initialization


java
Copy code
Queue<Long> queue = new LinkedList<>();
Set<Long> visited = new HashSet<>();

● 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.

5. Processing the BFS Queue

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();

● Dequeue the current number to process it.


● Each level in BFS corresponds to one move.

6. Check If N=0N = 0N=0


java
Copy code
if (current == 0) {
System.out.println(moves);
return;
}

● If the current number becomes 000, print the number of moves and terminate.

7. Generate Next States

● 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.

8. Increment the Moves Counter


java
Copy code
moves++;

● After processing all numbers at the current level, increment the moves counter.

9. Handle Edge Cases

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;
}

● Loops up to N\sqrt{N}N​to find divisors.


● Ensures that only states smaller than NNN are considered.

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.

You might also like