Exclusive Time of Functions LeetCode solution in Java

1
class Solution {
2

3
// Time Complexity: O(N) for looping through logs
4
// Space Complexity: O(N) for stack
5

6
public int[] exclusiveTime(int n, List<String> logs) {
7
if (n == 0) {
8
return new int[0];
9
}
10

11
int[] result = new int[n];
12

13
Stack<Pair<Integer, Integer>> stack = new Stack<>();
14

15
for (String s : logs) {
16
String[] sArr = s.split(":");
17
int functionId = Integer.parseInt(sArr[0]);
18
String startOrEnd = sArr[1];
19
int timestamp = Integer.parseInt(sArr[2]);
20

21
if (startOrEnd.equals("start")) {
22

23
// calculate previous in-progress length
24
if (!stack.empty()) {
25
Pair<Integer, Integer> pair = stack.peek();
26
int oldFunctionId = pair.getKey();
27
int oldTimestamp = pair.getValue();
28
result[oldFunctionId] += timestamp - oldTimestamp;
29
}
30

31
// add new start
32
stack.push(new Pair(functionId, timestamp));
33
} else {
34
// calculate current length
35
Pair<Integer, Integer> pair = stack.pop();
36
int oldTimestamp = pair.getValue();
37

38
result[functionId] += timestamp - oldTimestamp + 1;
39

40
// reset previous function's start
41
if (!stack.empty()) {
42
pair = stack.pop();
43
Pair<Integer, Integer> replacementPair = new Pair(pair.getKey(), timestamp + 1);
44
stack.push(replacementPair);
45
}
46
}
47
}
48

49
return result;
50
}
51
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0