Skip to main content
Back to problems
#522
Medium Algorithms

Longest uncommon subsequence ii

Array Hash Table Two Pointers String Sorting
44.5% acceptance
Feb 19, 2026
555
1386
Given an array of strings strs, return the length of the longest uncommon subsequence between them. If the longest uncommon subsequence does not exist, return -1. An uncommon subsequence between an array of strings is a string that is a subsequence of one string but not the others. A subsequence of a string s is a string that can be obtained after deleting any number of characters from s. For example, "abc" is a subsequence of "aebdc" because you can delete the underlined characters in "aebdc" to get "abc". Other subsequences of "aebdc" include "aebdc", "aeb", and "" (empty string).

Solution

Rust
Time O(2^n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn find_lu_slength(strs: Vec<String>) -> i32 {
    fn is_subseq(s: &[u8], t: &[u8]) -> bool {
      let mut j = 0;
      for &c in t {
        if j < s.len() && s[j] == c { j += 1; }
      }
      j == s.len()
    }
    let mut result = -1i32;
    for i in 0..strs.len() {
      let si = strs[i].as_bytes();
      let uncommon = strs.iter().enumerate().all(|(j, sj)| {
        j == i || !is_subseq(si, sj.as_bytes())
      });
      if uncommon { result = result.max(strs[i].len() as i32); }
    }
    result
  }
}