Skip to main content
Back to problems
#636
Medium Algorithms

Exclusive time of functions

Array Stack
66.2% acceptance
Feb 20, 2026
2318
2974
Return the exclusive time of each function in an array where each value represents the exclusive execution time for function i.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn exclusive_time(n: i32, logs: Vec<String>) -> Vec<i32> {
    let mut result = vec![0i32; n as usize];
    let mut stack: Vec<(usize, i32)> = Vec::new(); // (func_id, start_time)
    let mut prev_time = 0i32;
    for log in &logs {
      let parts: Vec<&str> = log.split(':').collect();
      let id: usize = parts[0].parse().unwrap();
      let is_start = parts[1] == "start";
      let time: i32 = parts[2].parse().unwrap();
      if is_start {
        if let Some(&(top_id, _)) = stack.last() {
          result[top_id] += time - prev_time;
        }
        stack.push((id, time));
        prev_time = time;
      } else {
        let (top_id, _) = stack.pop().unwrap();
        result[top_id] += time - prev_time + 1;
        prev_time = time + 1;
      }
    }
    result
  }
}