|
| 1 | +// 1376. Time Needed to Inform All Employees |
| 2 | +// 🟠 Medium |
| 3 | +// |
| 4 | +// https://leetcode.com/problems/time-needed-to-inform-all-employees/ |
| 5 | +// |
| 6 | +// Tags: Tree - Depth-First Search - Breadth-First Search |
| 7 | + |
| 8 | +use std::collections::VecDeque; |
| 9 | + |
| 10 | +struct Solution {} |
| 11 | +impl Solution { |
| 12 | + /// Reconstruct the tree, in this solution done creating an adjacency list |
| 13 | + /// in O(n), then use the tree to travel from the root to all the tree nodes |
| 14 | + /// keeping track of the time used. Return the maximum time to reach any node. |
| 15 | + /// |
| 16 | + /// Time complexity: O(n) - Recreate the tree, we could use tree nodes, but |
| 17 | + /// in Rust is quite verbose so I opted for an adjacency list instead, once |
| 18 | + /// we have a way to navigate from parents to children, the problem becomes |
| 19 | + /// a simple tree traversal, we can use BFS or DFS while keeping track of |
| 20 | + /// the time required to reach every employee, and return the maximum. |
| 21 | + /// Space complexity: O(n) - The subordinates vector is a 2D vector, but it |
| 22 | + /// will only have a total of n entries because each node is limited to |
| 23 | + /// having only one parent, we know the total number of edges = n-1. |
| 24 | + /// |
| 25 | + /// Runtime 39 ms Beats 86.67% |
| 26 | + /// Memory 8.7 MB Beats 33.33% |
| 27 | + pub fn num_of_minutes(n: i32, head_id: i32, manager: Vec<i32>, inform_time: Vec<i32>) -> i32 { |
| 28 | + let n = n as usize; |
| 29 | + let head_id = head_id as usize; |
| 30 | + let manager = manager |
| 31 | + .into_iter() |
| 32 | + .map(|x| x as usize) |
| 33 | + .collect::<Vec<usize>>(); |
| 34 | + let mut subordinates = vec![vec![]; n]; |
| 35 | + for employee in 0..n { |
| 36 | + if employee != head_id { |
| 37 | + subordinates[manager[employee]].push(employee); |
| 38 | + } |
| 39 | + } |
| 40 | + let mut res = 0; |
| 41 | + // BFS the time needed to inform all employees. |
| 42 | + let mut queue = VecDeque::from([(head_id, 0)]); |
| 43 | + while !queue.is_empty() { |
| 44 | + let (current_employee, current_time) = queue.pop_front().unwrap(); |
| 45 | + let time_to_informed = current_time + inform_time[current_employee]; |
| 46 | + if time_to_informed > res { |
| 47 | + res = time_to_informed; |
| 48 | + } |
| 49 | + for subordinate in subordinates[current_employee].iter() { |
| 50 | + queue.push_back((*subordinate, time_to_informed)); |
| 51 | + } |
| 52 | + } |
| 53 | + res |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +fn main() { |
| 58 | + let tests = [ |
| 59 | + (1, 0, vec![-1], vec![0], 0), |
| 60 | + (6, 2, vec![2, 2, -1, 2, 2, 2], vec![0, 0, 1, 0, 0, 0], 1), |
| 61 | + ]; |
| 62 | + for t in tests { |
| 63 | + assert_eq!(Solution::num_of_minutes(t.0, t.1, t.2, t.3), t.4); |
| 64 | + } |
| 65 | + println!("\x1b[92m» All tests passed!\x1b[0m") |
| 66 | +} |
0 commit comments