Approach
Stack-based processing
For Exclusive Time of Functions, the implementation keeps unresolved items in last-in, first-out order, often to match boundaries, parse structure, or maintain monotonic candidates.
- Define what every stack entry represents.
- Pop entries once the current item resolves or invalidates them.
- Push the current item with only the information later steps need.
Code notes
- 30 lines of C++ from the credited upstream file 636.cpp.
- The implementation visibly relies on sequence storage.
- 1 loop block detected.
Complexity
If each item is pushed and popped at most once, the stack work is linear.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<int> exclusiveTime(int n, vector<string>& logs) {4 vector<int> ans(n);5 stack<int> stack; 6 int prevTime;7 8 for (const string& log : logs) {9 10 const int colon1 = log.find_first_of(':');11 const int colon2 = log.find_last_of(':');12 13 const int id = stoi(log.substr(0, colon1)); 14 const char label = log[colon1 + 1]; 15 const int timestamp = stoi(log.substr(colon2 + 1)); 16 if (label == 's') {17 if (!stack.empty())18 ans[stack.top()] += timestamp - prevTime;19 stack.push(id);20 prevTime = timestamp;21 } else {22 ans[stack.top()] += timestamp - prevTime + 1, stack.pop();23 prevTime = timestamp + 1;24 }25 }26 27 return ans;28 }29};30