Python 1723.py
class Solution:
def minimumTimeRequired(self, jobs: List[int], k: int) -> int:
result = +inf
jobs.sort(reverse = True) # not needed, but allows for early exit
total = [ 0 ] * k # total time of each worker
def deeper(i): # assign i-th job to each worker and find best combination
nonlocal result
longest = max(total) # worker with highest load
if longest >= result: # we already had better assignments
return
# all jobs assigned
if i == len(jobs):
result = longest
return
# optimization: try to assign to workers with low load first
todo = sorted(range(k), key = lambda x : total[x]) # worker IDs, sorted by their load
# assign current job to each worker and start recursion
previous = -1 # workload of last worker
for t in todo:
# optimization: current worker has same workload as previous,
# no need assigning same job to both
if previous == total[t]:
continue
previous = total[t]
# assign job
total[t] += jobs[i]
# next job
deeper(i + 1)
# un-assign
total[t] -= jobs[i]
# let's go !
deeper(0)
return result
Difficulty
and has an acceptance rate of about 46% (90k+ submissions).
Typical patterns to solve this problem:
- Array
- Backtracking
- Bit Manipulation
- Bitmask
- Dynamic Programming
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The implementation solves the classic load-balancing problem: given a list of job durations and a fixed number of workers, it finds the smallest possible maximum workload (makespan) across all workers. The algorithm explores assignments via depth-first search while aggressively pruning branches that cannot improve the best solution found so far.
Key Steps
Sorting jobs in descending order
The job list is reordered so that the longest jobs are considered first. This ordering enables early detection of infeasible branches because large jobs quickly inflate a worker’s load.
jobs.sort(reverse=True) # not needed for correctness, but allows early exit
Initializing the search state
Two structures are prepared: result holds the best makespan discovered, initialized to positive infinity, and total records the cumulative workload for each of the k workers, all starting at zero.
result = +inf
total = [0] * k
Recursive depth-first assignment (deeper)
A nested function deeper(i) attempts to assign the i-th job to every worker and recurses to the next job. The function uses nonlocal result to update the global best makespan when a complete assignment is reached.
def deeper(i):
nonlocal result
longest = max(total)
if longest >= result:
return
if i == len(jobs):
result = longest
return
# worker ordering and pruning follow
Ordering workers by current load
Before trying assignments for the current job, the workers are sorted by their current total workload, from lightest to heaviest. This heuristic tends to keep the makespan low early in the search, increasing the chance of pruning later branches.
todo = sorted(range(k), key=lambda x: total[x])
Skipping workers with identical loads
When two workers have the same accumulated workload, assigning the current job to either of them leads to equivalent states. The variable previous remembers the load of the last examined worker; if the next worker shares that load, the iteration skips it, avoiding duplicate work.
previous = -1
for t in todo:
if previous == total[t]:
continue
previous = total[t]
# assignment and recursion
Assigning a job and backtracking
For each selected worker, the job duration is added to that worker’s total, the recursion proceeds to the next job, and finally the addition is undone to restore the state for the next iteration.
total[t] += jobs[i]
deeper(i + 1)
total[t] -= jobs[i]
Starting the search and returning the answer
The recursion is launched with the first job index, and after all feasible branches have been examined, the best makespan stored in result is returned.
deeper(0)
return result
Edge Cases Handled
When the job list is empty, the recursion reaches the base case immediately (i == len(jobs)) and records a makespan of zero, which is the correct answer.
If the number of workers k exceeds the number of jobs, the algorithm still creates a total array of size k. Since some workers will never receive a job, their load remains zero, and the makespan is determined solely by the assigned jobs.
When all jobs have identical durations, the sorting step leaves the list unchanged, but the duplicate-load skipping logic ensures that symmetric assignments are not explored repeatedly, preventing exponential blow-up in this uniform scenario.
If k equals one, the worker ordering step yields a single worker, and the recursion simply accumulates all job durations, resulting in the sum of the list as the makespan.
Performance Optimizations
The descending sort of jobs front-loads the largest durations, causing the longest >= result check to fire early for many branches, which dramatically reduces the search space.
The pruning condition if longest >= result: return eliminates any partial assignment that already exceeds the best known makespan, preventing deeper exploration of hopeless branches.
Sorting workers by their current load (todo = sorted(...)) directs the search toward balanced distributions first, increasing the likelihood that a good makespan is found early, which in turn tightens the pruning threshold.
Skipping workers with the same current load (if previous == total[t]: continue) removes redundant permutations of assignments that would lead to identical state configurations, cutting down the number of recursive calls without affecting correctness.
The combination of these heuristics yields a search that, while exponential in the worst case, performs efficiently for typical input sizes encountered in practice.
ELI5 - Simplified Explanation
Imagine you have a big pile of toys to put away into boxes. You have several friends helping you, and each friend has their own box. Some toys are heavy and take a long time to put away, while other toys are light and quick. Your goal is to make sure that no single friend is stuck working for a super long time compared to the others.
The computer looks at the list of toys and picks the heaviest one first. It tries giving that toy to the first friend, then checks how busy that friend is. Then it tries giving the next toy to a different friend to see if that works better. It is like playing a game of trying out different plans to see which one gets all the toys put away the fastest.
If the computer notices that a friend is already working longer than the best plan found so far, it stops and tries a different way. This keeps the work balanced so that everyone has a fair turn. The computer keeps moving toys around in its head, adding them to a friend's pile and then taking them out again to test a new idea, until it finds the perfect way to finish everything as quickly as possible.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||
| WalkCCC | C++ | Python | Java | |||||
| leetcode.ca | C++ | Python | Java | Go | ||||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 1986: Minimum Number of Work Sessions to Finish the Tasks
- problem 2323: Find Minimum Time to Finish All Jobs II
Solved On The Same Day
- problem 1559: Detect Cycles in 2D Grid
- problem 1573: Number of Ways to Split a String
- problem 1626: Best Team With No Conflicts
- problem 1705: Maximum Number of Eaten Apples
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality