1767. Find the Subtasks That Did Not Execute

Database

Explanation:

To solve this problem, we need to find the subtasks that did not execute given the information about the tasks that were executed in a specific order. We can use a stack to keep track of the tasks that are currently executing. While iterating through the executed tasks, we can simulate the execution and handle different cases accordingly.

  1. Initialize an empty stack to simulate the execution of tasks.
  2. Iterate through the executed tasks:
    • If the task is not a subtask, push it to the stack.
    • If the task is a subtask and the stack is not empty:
      • Pop tasks from the stack until we find a matching subtask or the stack becomes empty.
      • If a matching subtask is found, continue to the next executed task.
      • Otherwise, the subtask did not execute, so add it to the result.
  3. After iterating through all executed tasks, the remaining tasks in the stack are the subtasks that did not execute. :
class Solution {
    public List<Integer> findSubtasks(int[] executedTasks, int[] subtasks) {
        Stack<Integer> stack = new Stack<>();
        List<Integer> result = new ArrayList<>();
        
        int subIndex = 0;
        for (int task : executedTasks) {
            if (subIndex < subtasks.length && task == subtasks[subIndex]) {
                while (!stack.isEmpty() && stack.peek() != subtasks[subIndex]) {
                    result.add(stack.pop());
                }
                if (!stack.isEmpty()) {
                    stack.pop();
                }
                subIndex++;
            } else {
                stack.push(task);
            }
        }
        
        while (!stack.isEmpty()) {
            result.add(stack.pop());
        }
        
        return result;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.