DEV Community

Discussion on: A common coding interview question

Collapse
 
idanarye profile image
Idan Arye

Rust solution - works for any number of strings:

fn find_intersection(strings: &[&str]) -> String {
    if strings.is_empty() {
        // NOTE: mathematically speaking, the result here should be **all** the numbers - but we
        // obviously can't return that...
        return "".to_owned(); // no arrays to intersect
    }
    let mut iterators: Vec<_> = strings.iter().map(
        |s| s.split(',').map(|n| n.trim().parse::<isize>().unwrap())
    ).collect();
    let mut current_values = Vec::with_capacity(iterators.len());
    for it in iterators.iter_mut() {
        if let Some(value) = it.next() {
            current_values.push(value);
        } else {
            return "".to_owned(); // at least one array is empty => intersection is empty
        }
    }
    let mut result = Vec::<String>::new();

    loop {
        let (min_value, min_count) = {
            let mut min_value = current_values[0];
            let mut min_count = 1;
            for value in current_values.iter().skip(1) {
                use std::cmp::Ordering::*;
                match value.cmp(&min_value) {
                    Less => {
                        min_value = *value;
                        min_count = 1;
                    },
                    Equal => {
                        min_count += 1;
                    },
                    Greater => {},
                }
            };
            (min_value, min_count)
        };
        if min_count == current_values.len() {
            result.push(min_value.to_string());
        }
        for (current_value, it) in current_values.iter_mut().zip(iterators.iter_mut()) {
            if *current_value == min_value {
                if let Some(value) = it.next() {
                    assert!(*current_value <= value, "numbers must be ordered");
                    *current_value = value;
                } else {
                    return result.join(", ");
                }
            }
        }
    }
}
Collapse
 
gabgab2003 profile image
DownloadPizza

Is there any difference between

String::from("")

and

"".to_owned()

?

Collapse
 
idanarye profile image
Idan Arye

None that I'm aware of. I prefer "".to_owned() over String::from("") or "".to_string() to avoid the confusion of "why are you converting a string to a string?" that I've seen in some newbie Rust threads.