Skip to main content
Back to problems
#14
Easy Algorithms

Longest common prefix

Array String Trie
47.1% acceptance
Jan 12, 2026
21112
4912
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn longest_common_prefix(strs: Vec<String>) -> String {
    if strs.is_empty() {
      return String::new();
    }
    
    let first = strs[0].as_bytes();
    
    // Compare each character position across all strings
    for i in 0..first.len() {
      for s in strs.iter().skip(1) {
        let s_bytes = s.as_bytes();
        // If we've reached the end of current string or characters don't match
        if i >= s_bytes.len() || s_bytes[i] != first[i] {
          return String::from_utf8(first[..i].to_vec()).unwrap();
        }
      }
    }
    
    // All characters in first string are common prefix
    strs[0].clone()
  }
}