Bird
Raised Fist0
Interview Preptop-k-elementshardAmazonGoogleFacebook

Minimum Cost to Hire K Workers

Choose your preparation mode4 modes available
📋
Problem

Imagine you are managing a project and need to hire exactly K workers from a pool, each demanding a minimum wage and having a quality rating. You want to pay them fairly based on their quality but minimize the total cost.

You have n workers. Each worker has a quality and a minimum wage expectation. You want to hire exactly K workers to form a group. To pay them fairly, every worker in the group must be paid at least their minimum wage, and the pay must be proportional to their quality (i.e., if a worker has twice the quality, they get twice the pay). Find the minimum total wage to hire exactly K workers under these conditions.

1 ≤ n ≤ 10^51 ≤ K ≤ n1 ≤ quality[i], wage[i] ≤ 10^4
Edge cases: All workers have the same quality and wage → output is K times the minimum wageK equals n → must hire all workers, sum all wages proportionallyOne worker has extremely high wage but low quality → avoid if possible
</>
IDE
def mincostToHireWorkers(quality: list[int], wage: list[int], K: int) -> float:public double mincostToHireWorkers(int[] quality, int[] wage, int K)double mincostToHireWorkers(vector<int>& quality, vector<int>& wage, int K)function mincostToHireWorkers(quality, wage, K)
def mincostToHireWorkers(quality, wage, K):
    # Write your solution here
    pass
class Solution {
    public double mincostToHireWorkers(int[] quality, int[] wage, int K) {
        // Write your solution here
        return 0.0;
    }
}
#include <vector>
using namespace std;

double mincostToHireWorkers(vector<int>& quality, vector<int>& wage, int K) {
    // Write your solution here
    return 0.0;
}
function mincostToHireWorkers(quality, wage, K) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: NaN or crashNo handling of empty input or K=0, causing division by zero or index errors.✅ Add base case: if K == 0 or input arrays empty, return 0.0 immediately.
Wrong: Sum of wages without ratio adjustmentIgnoring wage-to-quality ratio and paying only minimum wages directly.✅ Calculate ratio = wage[i]/quality[i] and pay all workers at max ratio in chosen group.
Wrong: Including high ratio workers leading to higher costGreedy approach picking workers with lowest wages ignoring ratio constraints.✅ Sort by ratio and maintain heap of K smallest qualities to minimize total cost.
Wrong: Incorrect cost when all workers have identical ratioNot handling equal ratio case properly, leading to wrong subset or cost.✅ When ratios are equal, pick K workers with smallest quality sum and multiply by ratio.
Wrong: Timeout or TLEUsing brute force subset enumeration instead of sorting and heap approach.✅ Implement O(n log n) solution using sorting by ratio and max-heap for qualities.
✓
Test Cases
t1_01basic
Input{"quality":[10,20,5],"wage":[70,50,30],"K":2}
Expected105

Hire workers 0 and 2. Pay ratio is max(wage[i]/quality[i]) = max(70/10, 30/5) = 7. Total cost = 7 * (10 + 5) = 105.

t1_02basic
Input{"quality":[3,1,10,10,1],"wage":[4,8,2,2,7],"K":3}
Expected30.666666666666668

Hire workers with qualities [3,1,1] and wages [4,8,7]. Ratio max is 7/1=7. Total quality sum=5. Cost=7*5=35 is too high. Better is workers with qualities [3,10,10] and wages [4,2,2]. Ratio max=4/3=1.3333, sum quality=23, cost=30.6667 minimum.

t2_01edge
Input{"quality":[],"wage":[],"K":0}
Expected0

No workers to hire, cost is zero.

t2_02edge
Input{"quality":[5],"wage":[10],"K":1}
Expected10

Only one worker, must pay at least their wage, cost is 10.

t2_03edge
Input{"quality":[10,10,10],"wage":[20,20,20],"K":2}
Expected40

All workers have same quality and wage, cost is K times minimum wage = 2 * 20 = 40.

t3_01corner
Input{"quality":[1,2,3,4,5],"wage":[10,10,10,10,100],"K":3}
Expected50

Avoid hiring worker with high wage to quality ratio (worker 4). Best group is workers 0,1,3 with ratio 10/1=10 and sum quality 6, cost=50.

t3_02corner
Input{"quality":[4,4,4,4],"wage":[8,8,8,8],"K":4}
Expected32

All workers have same ratio 2.0, must hire all, cost = ratio * sum quality = 2 * 16 = 32.

t3_03corner
Input{"quality":[1,2,3],"wage":[3,6,9],"K":2}
Expected6

Workers have identical wage/quality ratio 3. Hiring any two workers costs 3 * sum of their qualities. Minimum sum quality for 2 workers is 2 (1+1), but qualities are 1 and 2, sum=3, cost=3*2=6.

t4_01performance
Input{"quality":[10000,9999,9998,9997,9996,9995,9994,9993,9992,9991,9990,9989,9988,9987,9986,9985,9984,9983,9982,9981,9980,9979,9978,9977,9976,9975,9974,9973,9972,9971,9970,9969,9968,9967,9966,9965,9964,9963,9962,9961,9960,9959,9958,9957,9956,9955,9954,9953,9952,9951,9950,9949,9948,9947,9946,9945,9944,9943,9942,9941,9940,9939,9938,9937,9936,9935,9934,9933,9932,9931,9930,9929,9928,9927,9926,9925,9924,9923,9922,9921,9920,9919,9918,9917,9916,9915,9914,9913,9912,9911,9910,9909,9908,9907,9906,9905,9904,9903,9902,9901,9900],"wage":[10000,9999,9998,9997,9996,9995,9994,9993,9992,9991,9990,9989,9988,9987,9986,9985,9984,9983,9982,9981,9980,9979,9978,9977,9976,9975,9974,9973,9972,9971,9970,9969,9968,9967,9966,9965,9964,9963,9962,9961,9960,9959,9958,9957,9956,9955,9954,9953,9952,9951,9950,9949,9948,9947,9946,9945,9944,9943,9942,9941,9940,9939,9938,9937,9936,9935,9934,9933,9932,9931,9930,9929,9928,9927,9926,9925,9924,9923,9922,9921,9920,9919,9918,9917,9916,9915,9914,9913,9912,9911,9910,9909,9908,9907,9906,9905,9904,9903,9902,9901,9900],"K":50}
⏱ Performance - must finish in 2000ms

Large input with n=100, K=50. Algorithm must run in O(n log n) time to avoid TLE.

Practice

(1/5)
1. Given the following Python code implementing Quickselect, what is the output of findKthLargest([4,1,3,2], 3)?
easy
A. 2
B. 3
C. 1
D. 4

Solution

  1. Step 1: Understand k and indexing

    k=3 means the 3rd largest element, so index k-1=2 in zero-based indexing.
  2. Step 2: Trace partition and quickselect

    Partition rearranges so elements > pivot are left; after recursive calls, the element at index 2 is 2.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    3rd largest in [4,1,3,2] is 2 [OK]
Hint: Remember zero-based index k-1 for kth largest [OK]
Common Mistakes:
  • Off-by-one error in k indexing
  • Confusing kth largest with kth smallest
  • Misunderstanding partition direction
2. Consider the following Python code that finds the maximum CPU load from a list of jobs. What is the value of max_load after processing all events for the input jobs = [[1,4,3], [2,5,4], [7,9,6]]?
def find_max_cpu_load(jobs):
    events = []
    for start, end, load in jobs:
        events.append((start, load))
        events.append((end, -load))
    events.sort(key=lambda x: x[0])

    current_load = 0
    max_load = 0
    for _, load_change in events:
        current_load += load_change
        max_load = max(max_load, current_load)
    return max_load

jobs = [[1,4,3], [2,5,4], [7,9,6]]
print(find_max_cpu_load(jobs))
easy
A. 7
B. 6
C. 9
D. 4

Solution

  1. Step 1: List all events sorted by time:

    Events: (1,+3), (2,+4), (4,-3), (5,-4), (7,+6), (9,-6)
  2. Step 2: Trace current_load and max_load through events:

    At 1: current_load=3, max_load=3; at 2: current_load=7, max_load=7; at 4: current_load=4, max_load=7; at 5: current_load=0, max_load=7; at 7: current_load=6, max_load=7; at 9: current_load=0, max_load=7.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Maximum overlap load is 7 at time 2 [OK]
Hint: Sum loads at event times, track max load [OK]
Common Mistakes:
  • Off-by-one in event processing
  • Ignoring negative load at job end
3. Consider the following Python code implementing the optimal approach for top K frequent words. Given the input words = ["apple", "banana", "apple", "orange", "banana", "banana"] and k = 2, what is the returned list?
easy
A. ["banana", "apple"]
B. ["banana", "orange"]
C. ["apple", "banana"]
D. ["apple", "orange"]

Solution

  1. Step 1: Count frequencies

    apple: 2, banana: 3, orange: 1; max_freq = 3
  2. Step 2: Fill buckets and sort within buckets

    buckets[3] = ["banana"], buckets[2] = ["apple"], buckets[1] = ["orange"]; iterate from freq=3 down
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Top 2 frequent words are banana (3), apple (2) [OK]
Hint: Trace frequency buckets from highest to lowest [OK]
Common Mistakes:
  • Confusing lex order with frequency order
  • Off-by-one in bucket indices
  • Returning words in ascending frequency order
4. What is the time complexity of the heap-based approach to find the k-th smallest pair distance in an array of size n?
medium
A. O(n log n + k log n)
B. O(n^2 log n)
C. O(n log n + k log k)
D. O(n log n + k n)

Solution

  1. Step 1: Analyze sorting and heap initialization

    Sorting takes O(n log n). Initial heap push for n-1 pairs is O(n log n) but dominated by sorting.
  2. Step 2: Analyze k iterations of heap operations

    Each pop and push operation costs O(log n), repeated k times -> O(k log n).
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Heap size bounded by n, so log n factor dominates [OK]
Hint: Heap operations cost log n, not log k or n^2 [OK]
Common Mistakes:
  • Confusing k log k with k log n
  • Assuming O(n^2 log n) due to pairs
  • Ignoring heap size limits
5. The following code attempts to implement the optimal bucket sort approach for top k frequent elements. Identify the line that contains a subtle bug that can cause incorrect results or runtime errors.
medium
A. Line updating frequency dictionary with freq.get(num, 0) + 1
B. Line iterating over freq.items() to append elements to buckets
C. Line creating buckets with size max_freq instead of max_freq + 1
D. Line iterating buckets from max_freq - 1 down to 0

Solution

  1. Step 1: Check bucket list size

    Buckets are created with size max_freq, but frequencies range from 1 to max_freq inclusive, so index max_freq is needed.
  2. Step 2: Consequence of incorrect bucket size

    Accessing buckets[count] where count == max_freq causes IndexError or missing elements if bucket list is too small.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Bucket list must have max_freq + 1 slots to index frequencies correctly [OK]
Hint: Bucket size must be max_freq + 1 to include max frequency [OK]
Common Mistakes:
  • Off-by-one bucket size
  • Misindexing buckets causing runtime errors
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard