Neat solution in Ruby with explanation

  • 0

    For Ruby, it's super easy to parse log string. So I decide to use it for this problem.

    This problem is similar to the problems of parsing strings like "(()())". A function begin corresponds to "(" and an end to ")". So stack is perfect for this and the problem ensures that the log strings are all valid. But the different point is when you close a pair of "()", you need to deduct the time of others in between them. However it's easy to because the top one's parent is just the one immediately below the top one. See code:

    def exclusive_time(n, logs)
      res =, 0)
      stk = []
      logs.each do |log|
        num, act, ts = log.split ':'
        num = num.to_i
        ts = ts.to_i
        if act == 'start'
          stk.push({:n => num, :ts => ts})
          l = stk.pop
          t = ts - l[:ts] + 1
          res[num] += t
          top = stk.last
          if top
            res[top[:n]] -= t

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.