Problem 1723

Abstract / Summary

Given a list of job durations and a limit on how many jobs can be done at once find the shortest time to complete all jobs

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
40 lines | 1487 bytes | submitted January 22, 2024 | GitHub   66% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 46% (90k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Backtracking
  • Bit Manipulation
  • Bitmask
  • Dynamic Programming
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 7.12 | σ = 1.42

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
22 links | 12 authors | 7 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

5 solutions   January 22, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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