Skip to content

[BUG] - 636. Exclusive Time of Functions #26416

@jilsonjoseph

Description

@jilsonjoseph

LeetCode Username

spraycan

Problem Number, Title, and Link

https://leetcode.com/problems/exclusive-time-of-functions/description/

Bug Category

Editorial

Bug Description

The Approach 1 TLE solution has a bug in the Java code
It fails for the below testcase
n =2 ["0:start:0","0:end:2","1:start:5","1:end:6"]

Expected result for the above test case: [3, 2]
Actual: Runtime Error (EmptyStackException)
The code doesn't check if the stack is empty before stack.peek() call

Language Used for Code

Java

Code used for Submit/Run operation

public class Solution {
    public int[] exclusiveTime(int n, List < String > logs) {
        Stack < Integer > stack = new Stack < > ();
        int[] res = new int[n];
        String[] s = logs.get(0).split(":");
        stack.push(Integer.parseInt(s[0]));
        int i = 1, time = Integer.parseInt(s[2]);
        while (i < logs.size()) {
            s = logs.get(i).split(":");
            while (time < Integer.parseInt(s[2])) {
                res[stack.peek()]++;      // issue is here, stack can be empty here
                time++;
            }
            if (s[1].equals("start"))
                stack.push(Integer.parseInt(s[0]));
            else {
                res[stack.peek()]++;
                time++;
                stack.pop();
            }
            i++;
        }
        return res;
    }
}

Expected behavior

An additional if case mentioned below can be added for stack empty scenario

if(stack.isEmpty()){ 
     stack.push(Integer.parseInt(s[0]));
     time = Integer.parseInt(s[2]);
     continue;
}

Screenshots

No response

Additional context

I have described the issue here https://leetcode.com/problems/exclusive-time-of-functions/editorial/comments/2802116
with the corrected code.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions