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: Group Tasks [3,1,4] with sessionTime=5Input Tasks3 hrs1 hr4 hrsOptimal GroupingSession 1: [4,1] = 5 hrsExactly fits session limitSession 2: [3] = 3 hrsUnder session limitResult: 2sessions❌ Alternative: 3 sessions [4], [3], [1] - not optimalGoal: Pack tasks efficiently to minimize sessions🎯 Key: This is a bin packing optimization problem
Understanding the Visualization
1
Input Tasks
Array of task durations and maximum session time
2
Group Optimally
Find best way to group tasks without exceeding session limits
3
Count Sessions
Return minimum number of sessions required
Key Takeaway
🎯 Key Insight: This is essentially a bin packing problem where we minimize the number of bins (sessions) needed to pack all items (tasks) with capacity constraints.
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