#1986

Minimum Number of Work Sessions to Finish the Tasks

Medium
ArrayDynamic ProgrammingBacktrackingBit ManipulationBitmaskDynamic ProgrammingBit Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * 2^n)
Space
O(1)
O(2^n)
💡

Intuition

Time O(n * 2^n)Space O(2^n)

The optimal solution uses dynamic programming with bit masking to efficiently track which tasks have been completed. This reduces the number of states we need to explore and allows us to reuse previously computed results.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP array to store the minimum sessions needed for each state of completed tasks.
  2. 2Step 2: Iterate through all possible states of completed tasks using bit masking.
  3. 3Step 3: For each state, try adding tasks to the current session and update the DP array accordingly.
solution.py15 lines
1# Full working Python code
2def minSessions(tasks, sessionTime):
3    n = len(tasks)
4    dp = [float('inf')] * (1 << n)
5    dp[0] = 0
6    for mask in range(1 << n):
7        total = 0
8        for i in range(n):
9            if mask & (1 << i) == 0:
10                if total + tasks[i] <= sessionTime:
11                    total += tasks[i]
12                else:
13                    dp[mask | (1 << i)] = min(dp[mask | (1 << i)], dp[mask] + 1)
14    return dp[(1 << n) - 1]
15

Complexity note: The time complexity is O(n * 2^n) because we explore all possible states of tasks using bit masking, and for each state, we may check all tasks. The space complexity is O(2^n) due to the DP array storing results for each state.

  • 1Dynamic programming can significantly reduce the number of states to explore.
  • 2Bit masking is a powerful technique for problems involving subsets.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.