Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

636. Exclusive Time of Functions

ArrayStack

Explanation

To solve this problem, we can simulate the execution of functions using a stack to keep track of the start and end times of each function. We iterate through the logs and update the exclusive time for each function accordingly.

Here's the algorithm:

  1. Initialize an array exclusiveTime of size n to store the exclusive time for each function.
  2. Initialize a stack stack to keep track of functions.
  3. Iterate through each log:
    • Split the log into function ID, event (start/end), and timestamp.
    • If the event is a start event:
      • If the stack is not empty, update the exclusive time of the function at the top of the stack.
      • Push the function ID and timestamp onto the stack.
    • If the event is an end event:
      • Update the exclusive time of the function at the top of the stack.
      • Pop the function ID and timestamp from the stack.
  4. Return the exclusiveTime array.

Time complexity: O(logs.length) Space complexity: O(n)

class Solution {
    public int[] exclusiveTime(int n, List<String> logs) {
        int[] exclusiveTime = new int[n];
        Stack<int[]> stack = new Stack<>();

        for (String log : logs) {
            String[] parts = log.split(":");
            int functionId = Integer.parseInt(parts[0]);
            String event = parts[1];
            int timestamp = Integer.parseInt(parts[2]);

            if (event.equals("start")) {
                if (!stack.isEmpty()) {
                    int[] prev = stack.peek();
                    exclusiveTime[prev[0]] += timestamp - prev[1];
                }
                stack.push(new int[]{functionId, timestamp});
            } else {
                int[] current = stack.pop();
                exclusiveTime[functionId] += timestamp - current[1] + 1;

                if (!stack.isEmpty()) {
                    stack.peek()[1] = timestamp + 1;
                }
            }
        }

        return exclusiveTime;
    }
}

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.