Minimum Number of Work Sessions to Finish the Tasks - Problem

You are given n tasks with their respective time requirements in an integer array tasks, where tasks[i] represents the hours needed to complete the i-th task.

A work session allows you to work for at most sessionTime consecutive hours before taking a break. Your goal is to complete all tasks following these rules:

  • If you start a task in a work session, you must complete it in the same session
  • You can start a new task immediately after finishing the previous one
  • You may complete tasks in any order

Return the minimum number of work sessions needed to finish all tasks.

Note: The session time is guaranteed to be at least as large as the maximum task duration.

Input & Output

Example 1 — Basic Case
$ Input: tasks = [1,2,3], sessionTime = 3
Output: 2
💡 Note: You can finish tasks in 2 sessions: Session 1: [3] (3 hours), Session 2: [1,2] (3 hours total)
Example 2 — More Tasks
$ Input: tasks = [3,1,4], sessionTime = 5
Output: 2
💡 Note: Optimal grouping: Session 1: [4,1] (5 hours), Session 2: [3] (3 hours). Total: 2 sessions
Example 3 — Perfect Fit
$ Input: tasks = [2,2,2], sessionTime = 4
Output: 2
💡 Note: Session 1: [2,2] (4 hours), Session 2: [2] (2 hours). Cannot fit all three 2-hour tasks in one 4-hour session

Constraints

  • 1 ≤ tasks.length ≤ 14
  • 1 ≤ tasks[i] ≤ 10
  • max(tasks[i]) ≤ sessionTime ≤ 15

Visualization

Tap to expand
Minimum Work Sessions to Finish Tasks INPUT tasks array: 1 i=0 2 i=1 3 i=2 sessionTime: 3 hours Task durations visualized: 1 hr 2 hr 3 hr Total: 1+2+3 = 6 hours ALGORITHM STEPS 1 Sort Descending [3, 2, 1] - largest first 2 Try Session 1 Add task[0]=3, sum=3 Session 1: [3] = 3/3 3 Try Session 2 Add task[1]=2, sum=2 4 Fit task[2]=1 2+1=3 fits in Session 2 Session 2: [2,1] = 3/3 Bin Packing Strategy: Greedy fit tasks into sessions FINAL RESULT Sessions needed: Session 1 Task: 3 hrs Session 2 2 1 Output: 2 OK - Optimal! Key Insight: This is a bin packing problem solved optimally using bitmask DP or backtracking with pruning. For small inputs, greedy approach (sort descending, fit tasks into sessions) often works. Time complexity: O(n! * n) for brute force, O(3^n) for optimal DP. Space: O(2^n) for memoization. TutorialsPoint - Minimum Number of Work Sessions to Finish the Tasks | Optimal Solution
Asked in
Meta 15 Amazon 12 Google 8 Microsoft 6
28.5K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen