Function Exclusive Time Calculation
Function Exclusive Time Calculation

Approach
Functions executing in time order form a call stack structure. This means we can solve it by simulating function calls with a simple stack implementation following the problem description. The main challenge lies in calculating the time spent correctly—just read the requirements carefully.
Solution
#include <sstream>
using namespace std;
class Solution {
public:
vector<int> exclusiveTime(int n, vector<string>& logs) {
vector<int> res(n, 0);
stack<pair<int, int>> st;
string sno;
string state;
string time;
int id;
int t;
for(string s : logs) {
// Split log string
stringstream ss (s);
getline(ss, sno, ':');
getline(ss, state, ':');
getline(ss, time, ':');
id = stoi(sno);
t = stoi(time);
if (state == "start") {
// Start call, push to stack
st.push(make_pair(id, t));
} else {
auto p = st.top();
st.pop();
// Start is the head of that moment, end is the tail of finish moment
t = t - p.second + 1;
res[p.first] += t;
// Upper function time needs to subtract inner running function time
if (!st.empty())
res[st.top().first]-=t;
}
}
return res;
}
};Key Takeaways
This exercise reinforces basic STL string operations and stack-based function call simulation techniques.
#stack #string