A subsequence of a string is what is left after deleting zero or more of its letters, keeping the rest in order. Call a string an uncommon subsequence of a and b when it is a subsequence of one of them and not of the other.
Find the longest such string for the pair a, b and return how many letters it has. If no string qualifies, return -1.
Example 1
Input: a = "lamp", b = "lump" Output: 4 Why: "lamp" is not a subsequence of "lump"
2 more examples and the constraints
Example 2
Input: a = "sun", b = "sunset" Output: 6 Why: "sunset" cannot be made from "sun"
Example 3
Input: a = "moon", b = "moon" Output: -1 Why: equal strings share every subsequence
Constraints
- Each of a and b has between 1 and 100 letters
- Both strings use only the letters a to z, in lowercase
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Test each whole stringO(n + m)
- Equal or notO(min(n, m))
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Letter reads for two 100-letter strings | Verdict |
|---|---|---|---|
| Test each whole string | O(n + m) | Passes; two subsequence scans | |
| Equal or not | O(min(n, m)) | Best; one comparison |
n and m = the lengths of a and b.
Edge cases to test
- Equal strings. Every subsequence of one is a subsequence of the other, so the answer is -1.
- One string inside the other. "ace" fits inside "abcde", but "abcde" does not fit inside "ace", so the answer is 5.
- Same letters, different order. "ab" and "ba" differ, so the answer is 2.
- Single letters. "x" and "y" give 1; "k" and "k" give -1.
Common mistakes
- Returning the shorter length, or len(a) every time, instead of the longer one.
- Starting to list every subsequence: there are 2^100 of them.
- Returning 0 instead of -1 when the strings are equal.
How to talk through it
- 1Clarify. A subsequence keeps order but may skip letters. Is the empty string ever an answer? No, it is shared by both.
- 2Start from the longest. The longest subsequence of a string is the whole string, so test the two whole strings first.
- 3Test each one. A whole string is uncommon when it is not a subsequence of the other one.
- 4Simplify. Both tests fail only when the strings are equal, so the answer is -1 for equal strings and the longer length otherwise.
- 5Test out loud. Run equal strings, a prefix pair and a same-length pair.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?