Order Tasks So Each Team's Tasks Stay Contiguous and Dependencies Hold

Last updated: November 29, 2026

Quick Overview

Each of n tasks belongs to at most one team (or none), and each task lists tasks that must come before it. Return an ordering where every team's tasks appear consecutively and all dependencies hold, or an empty list if impossible.

Meta
Coding & Algorithms
Software Engineer
Meta
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


Each of n tasks belongs to at most one team (or none), and each task lists tasks that must come before it. Return an ordering where every team's tasks appear consecutively and all dependencies hold, or an empty list if impossible.

A hard Meta onsite question modeled on planning a quarter of work where each team wants its tasks in one contiguous block. The interviewer checks that you decompose it into two levels of topological sort (teams, then tasks within each team) and handle tasks with no team by giving each its own singleton group.

What the Interviewer Expects
  • Assign each teamless task a unique new group id
  • Build a group-level graph from cross-group dependencies
  • Build an item-level graph from all dependencies
  • Topologically sort both, then bucket items by group
  • Return empty if either sort detects a cycle
Key Topics to Cover
two-level topological sort
grouping
Kahn's algorithm
cycle detection
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Why is it safe to sort all items globally and then bucket them by group?
  • How would you minimize the number of team switches if contiguity were a soft goal?
  • What changes if a task can belong to multiple teams?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Input: n, m teams, group[i] in 0..m-1 or -1, and before[i], a list of tasks that must precede i.
  • Output: a permutation of 0..n-1 that keeps each team's tasks contiguous and respect...
High-Level Design
  1. Singleton groups. Give every -1 task its own new group id, so every task has exactly one group.
  2. Two graphs.
    • Item graph: edge p -> i for each p in before[i].
    • Group graph...

Submit Your Answer
Markdown supported