Leetcode #2462: Total Cost to Hire K Workers
In this guide, we solve Leetcode #2462 Total Cost to Hire K Workers in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given a 0-indexed integer array costs where costs[i] is the cost of hiring the ith worker. You are also given two integers k and candidates.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Two Pointers, Simulation, Heap (Priority Queue)
Intuition
The constraints hint that we can reason about two ends of the data at once, which is perfect for a two-pointer scan.
Moving one pointer at a time keeps the invariant intact and avoids nested loops.
Approach
Place pointers at the left and right ends and move them based on the comparison or target condition.
This yields a clean linear pass after any required sorting.
Steps:
- Set left and right pointers.
- Move a pointer based on the condition.
- Update the best answer while scanning.
Example
Input: costs = [17,12,10,2,7,2,11,20,8], k = 3, candidates = 4
Output: 11
Explanation: We hire 3 workers in total. The total cost is initially 0.
- In the first hiring round we choose the worker from [17,12,10,2,7,2,11,20,8]. The lowest cost is 2, and we break the tie by the smallest index, which is 3. The total cost = 0 + 2 = 2.
- In the second hiring round we choose the worker from [17,12,10,7,2,11,20,8]. The lowest cost is 2 (index 4). The total cost = 2 + 2 = 4.
- In the third hiring round we choose the worker from [17,12,10,7,11,20,8]. The lowest cost is 7 (index 3). The total cost = 4 + 7 = 11. Notice that the worker with index 3 was common in the first and last four workers.
The total hiring cost is 11.
Python Solution
class Solution:
def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
n = len(costs)
if candidates * 2 >= n:
return sum(sorted(costs)[:k])
pq = []
for i, c in enumerate(costs[:candidates]):
heappush(pq, (c, i))
for i in range(n - candidates, n):
heappush(pq, (costs[i], i))
heapify(pq)
l, r = candidates, n - candidates - 1
ans = 0
for _ in range(k):
c, i = heappop(pq)
ans += c
if l > r:
continue
if i < l:
heappush(pq, (costs[l], l))
l += 1
else:
heappush(pq, (costs[r], r))
r -= 1
return ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.