Simple Java solution - stack


  • 0

    The idea is simple - Use a stack to mimic a function call stack. Stack top will always yield the currently executing fn.
    Also keep track of the currently exec function's start/restart timestamp.

    public class Solution {
        public int[] exclusiveTime(int n, List<String> logs) {
            int[] result = new int[n];
            Stack<Integer> stack = new Stack<>();
            String[] log0 = logs.get(0).split(":");
            
            stack.push(Integer.parseInt(log0[0]));
            int currExStartTS = Integer.parseInt(log0[2]);
            for(int i = 1; i < logs.size(); i++) {
                String[] logi = logs.get(i).split(":");
                int logi_fn = Integer.parseInt(logi[0]);
    			int logi_ts = Integer.parseInt(logi[2]);
                if(logi[1].equals("start")) {
                    if(!stack.isEmpty()) { //check if there is no currently executing fn
                        int currFn = stack.peek();    
                        result[currFn] += logi_ts - currExStartTS;
                    }
                    currExStartTS = logi_ts;
                    stack.push(logi_fn);
                }
                else {
                    int endedFn = stack.pop();
                    result[endedFn] += logi_ts - currExStartTS + 1;  
                    currExStartTS = logi_ts + 1;
                }
            }
            
            return result;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.