Problem solution · C++

Exclusive Time of Functions

Exclusive Time of Functions: a C++ solution using stack-based processing. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Stack-based processing
Source
walkccc LeetCode Solutions
Length
30 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Define what every stack entry represents.
  2. Pop entries once the current item resolves or invalidates them.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeExclusive Time of Functions · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  vector<int> exclusiveTime(int n, vector<string>& logs) {    vector<int> ans(n);    stack<int> stack;  // [oldest_id, ..., latest_id]    int prevTime;     for (const string& log : logs) {      // Get the seperators' indices.      const int colon1 = log.find_first_of(':');      const int colon2 = log.find_last_of(':');      // Get the function_id, the label, and the timestamp.      const int id = stoi(log.substr(0, colon1));  // {function_id}      const char label = log[colon1 + 1];  // {"s" ("start") | "e" ("end") }      const int timestamp = stoi(log.substr(colon2 + 1));  // {timestamp}      if (label == 's') {        if (!stack.empty())          ans[stack.top()] += timestamp - prevTime;        stack.push(id);        prevTime = timestamp;      } else {        ans[stack.top()] += timestamp - prevTime + 1, stack.pop();        prevTime = timestamp + 1;      }    }     return ans;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗