Apple Interview Question: Task Dependency Resolution via Topological Sort (Apple OA / Coding Interview / Dependency Graph)

26 Views
No Comments

We have a list of tasks. Each task can depend on other tasks.
If task A depends on task B, then B should run before A.

Implement the method getTaskWithDependencies such that it returns a list of task names in the correct order.

Example:
If we want to execute task "application A", the method should return:

["storage", "mongo", "application A"]

The Java program is expected to be executed successfully.


List of Tasks

- name: application A
  dependsOn:
    - mongo

- name: storage

- name: mongo
  dependsOn:
    - storage

- name: memcache

- name: application B
  dependsOn:
    - memcache

Function to Implement (Java)

// Return the execution order for a given target, with all dependencies first.
private static List<String> getTaskWithDependencies(List<Task> tasks, String dependsOn);

Task Class (Given)

class Task {
  private final String name;
  private final List<String> dependsOn;

  Task(String name) {this(name, new ArrayList<>()); }
  Task(String name, List<String> dependsOn) {
    this.name = name;
    this.dependsOn = dependsOn;
  }
  public String getName() { return this.name;}
  public List<String> getDependsOn() { return this.dependsOn;}
}

✅ Input / Output Examples

Input Example 1 — target: "application A"

tasks:
  - name: application A
    dependsOn: [mongo]
  - name: storage
  - name: mongo
    dependsOn: [storage]
  - name: memcache
  - name: application B
    dependsOn: [memcache]
target: "application A"

Expected Output

["storage", "mongo", "application A"]

Input Example 2 — target: "application B"

tasks:
  - name: application A
    dependsOn: [mongo]
  - name: storage
  - name: mongo
    dependsOn: [storage]
  - name: memcache
  - name: application B
    dependsOn: [memcache]
target: "application B"

Expected Output

["memcache", "application B"]

This problem asks you to resolve dependencies and return a valid execution order for a target task, where all prerequisites appear before the task.
It maps directly to Topological Sorting on a dependency graph.

Key points:

  • Use DFS with post-order and a visited set (or Kahn’s algorithm).
  • Ensure each dependency is emitted once and before the task.
  • (If required) add cycle detection with visiting/visited states.

This is a typical Apple OA / Interview question that evaluates understanding of dependency graphs, scheduling, and topological order.

The VOprep team has long accompanied candidates through various major company OAs and VOs, including Apple, Google, Amazon, Citadel, SIG, providing real-time voice assistance, remote practice, and interview pacing reminders to help you stay smooth during critical moments. If you are preparing for Tiktok or similar engineering-focused companies, you can check out our customized support plans—from coding interviews to system design, we offer full guidance to help you succeed.

END
 0