Leetcode 636. Exclusive Time of Functions
On a single-threaded CPU, we have a set of n
functions that are to be executed. Each function has a unique ID between 0 and n-1
.
Function calls are stored in a log stack in the order they were called. The log array is given in the following format:
log[i] = "function_id:start_or_end:timestamp"
, for example: "0:start:0"
or "1:end:4"
.Each function has two entries, one with start
and one with end
. When a function starts or ends, it does not overlap with any other function.
The exclusive time
of a function is the time spent running that function, excluding the time spent running other functions called within.
Return the exclusive time of each function in an array, where the value at the ith index represents the exclusive time of the function with the ID i
.
start
and end
log entries be in any particular order?
entry
look like?
"function_id:start_or_end:timestamp"
.#include <vector>
#include <string>
#include <stack>
#include <sstream>
#include <iostream>
using namespace std;
vector<int> exclusiveTime(int n, vector<string>& logs) {
vector<int> result(n, 0);
stack<int> callStack;
int prevTime = 0;
for (const string& log : logs) {
istringstream iss(log);
string idStr, type, timeStr;
getline(iss, idStr, ':');
getline(iss, type, ':');
getline(iss, timeStr, ':');
int id = stoi(idStr);
int time = stoi(timeStr);
if (type == "start") {
if (!callStack.empty()) {
result[callStack.top()] += time - prevTime;
}
callStack.push(id);
prevTime = time;
} else {
result[callStack.top()] += time - prevTime + 1;
callStack.pop();
prevTime = time + 1;
}
}
return result;
}
// Helper function to print vector of integers
void printVector(const vector<int>& v) {
for (int num : v) {
cout << num << " ";
}
cout << endl;
}
int main() {
vector<string> logs = {
"0:start:0",
"1:start:2",
"1:end:5",
"0:end:6"
};
int n = 2;
vector<int> result = exclusiveTime(n, logs);
printVector(result); // Output: [3, 4]
return 0;
}
result
vector initialized to 0 to store exclusive times.stack
to keep track of function calls.prevTime
to manage the previous timestamp.id
, type
, and timestamp
."start"
type:
id
onto the stack.prevTime
."end"
type:
prevTime
.result
vector containing exclusive times for each function.m
is the number of log entries. This is because we process each log entry exactly once.n
is the number of functions.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?