|
| 1 | +//! # LeetCode Problem: 599 - Minimum Index Sum of Two Lists |
| 2 | +//! |
| 3 | +//! Difficulty: Easy |
| 4 | +//! |
| 5 | +//! Link: https://leetcode.com/problems/minimum-index-sum-of-two-lists/ |
| 6 | +//! |
| 7 | +//! ## Complexity Analysis |
| 8 | +//! - Time Complexity: O(n + m) - We traverse the lists containing n and m elements exactly twice. |
| 9 | +//! - Space Complexity: O(min(n, m)) - The extra space required depends on the number of items |
| 10 | +//! stored in the hash map, which is the size of the smaller list. |
| 11 | +pub struct Solution; |
| 12 | + |
| 13 | +impl Solution { |
| 14 | + pub fn find_restaurant(list1: Vec<String>, list2: Vec<String>) -> Vec<String> { |
| 15 | + let mut indices = std::collections::HashMap::new(); |
| 16 | + let mut min_sum = list1.len() + list2.len(); |
| 17 | + let mut result: Vec<String> = vec![]; |
| 18 | + |
| 19 | + for (i, element) in list1.iter().enumerate() { |
| 20 | + indices.insert(element, i); |
| 21 | + } |
| 22 | + |
| 23 | + for (i, element) in list2.iter().enumerate() { |
| 24 | + if let Some(&j) = indices.get(element) { |
| 25 | + let sum = i + j; |
| 26 | + if sum < min_sum { |
| 27 | + min_sum = sum; |
| 28 | + result.clear(); |
| 29 | + result.push(element.clone()); |
| 30 | + } else if sum == min_sum { |
| 31 | + result.push(element.clone()); |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + result |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +#[cfg(test)] |
| 40 | +mod tests { |
| 41 | + use super::Solution; |
| 42 | + |
| 43 | + #[test] |
| 44 | + fn test_find_restaurant() { |
| 45 | + let test_cases = [ |
| 46 | + ( |
| 47 | + vec!["happy", "sad", "good"], |
| 48 | + vec!["sad", "happy", "good"], |
| 49 | + vec!["sad", "happy"], |
| 50 | + ), |
| 51 | + ( |
| 52 | + vec!["Shogun", "Tapioca Express", "Burger King", "KFC"], |
| 53 | + vec!["KFC", "Shogun", "Burger King"], |
| 54 | + vec!["Shogun"], |
| 55 | + ), |
| 56 | + ( |
| 57 | + vec!["Shogun", "Tapioca Express", "Burger King", "KFC"], |
| 58 | + vec![ |
| 59 | + "Piatti", |
| 60 | + "The Grill at Torrey Pines", |
| 61 | + "Hungry Hunter Steakhouse", |
| 62 | + "Shogun", |
| 63 | + ], |
| 64 | + vec!["Shogun"], |
| 65 | + ), |
| 66 | + ]; |
| 67 | + for (idx, (list1, list2, expected)) in test_cases.iter().enumerate() { |
| 68 | + let list1_strings: Vec<String> = list1.iter().map(|&s| s.to_string()).collect(); |
| 69 | + let list2_strings: Vec<String> = list2.iter().map(|&s| s.to_string()).collect(); |
| 70 | + let expected_strings: Vec<String> = expected.iter().map(|&s| s.to_string()).collect(); |
| 71 | + let result = Solution::find_restaurant(list1_strings, list2_strings); |
| 72 | + assert_eq!( |
| 73 | + result, expected_strings, |
| 74 | + "Test case #{}: with list1 = {:?}, list2 = {:?}, expected {:?}, got {:?}", |
| 75 | + idx, list1, list2, expected, result |
| 76 | + ); |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments