← Home

521. Longest Uncommon Subsequence I

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
521

This is one of those problems where the clean idea matters more than the amount of code. For 521. Longest Uncommon Subsequence I, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

The notes already sitting in the source point us in the right direction:

  • time: O(min(x,y)), space: O(1)

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are findLUSlength.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(min(x,y)), space: O(1)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//time: O(min(x,y)), space: O(1)
02//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Longest Uncommon Subsequence I .
03//Memory Usage: 8.5 MB, less than 40.00% of C++ online submissions for Longest Uncommon Subsequence I .
04class Solution {
05public:
06    int findLUSlength(string a, string b) {
07        if(a != b){
08            return max(a.size(), b.size());
09        }
10        return -1;
11    }
12};

Cost

Complexity

Time
O(min(x,y)), space: O(1)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.