Migratory Birds

  • + 1 comment

    Rust best solution

    If you’re looking for solutions to the 3-month preparation kit in either Python or Rust, you can find them below: my solutions

    fn migratory_birds(arr: &[i32]) -> i32 {
        //Time complexity: O(n)
        //Space complexity (ignoring input): O(1). You could use a frequency array instead
        //of a dictionary and use even less space
        let mut birds_hash = std::collections::HashMap::new();
        for &bird in arr {
            match birds_hash.get(&bird) {
                Some(value) => birds_hash.insert(bird, value + 1),
                None => birds_hash.insert(bird, 1),
            };
        }
    
        struct BirdInfo {
            bird: i32,
            frequency: i32,
        }
        let mut most_frequent = BirdInfo {
            bird: 6,
            frequency: 0,
        };
        for (bird, frequency) in birds_hash.iter() {
            if frequency > &most_frequent.frequency {
                most_frequent.bird = *bird;
                most_frequent.frequency = *frequency
            }
            if (frequency == &most_frequent.frequency) & (bird < &most_frequent.bird) {
                most_frequent.bird = *bird;
            }
        }
        most_frequent.bird
    }