#521

Longest Uncommon Subsequence I

Easy
StringString comparisonDynamic programming (for more complex subsequence problems)
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(2^n)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages the fact that if the two strings are equal, there are no uncommon subsequences. If they are different, the longer string itself is the longest uncommon subsequence.

⚙️

Algorithm

3 steps
  1. 1Step 1: Check if strings a and b are equal.
  2. 2Step 2: If they are equal, return -1.
  3. 3Step 3: If they are not equal, return the length of the longer string.
solution.py6 lines
1# Full working Python code
2
3def longest_uncommon_subsequence(a, b):
4    if a == b:
5        return -1
6    return max(len(a), len(b))

Complexity note: The time complexity is O(n) due to the string comparison and length calculation, while the space complexity is O(1) since we are not using any additional data structures.

  • 1If the two strings are equal, there are no uncommon subsequences.
  • 2The longest uncommon subsequence is simply the longer of the two strings if they are different.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.