Longest common subsequence calculator
Find the length and one witness for the longest in-order match between two strings. Your inputs stay on your device.
Set up your task
Starting local processing
Ready. Processing stays in this browser.
2 Your result
Your result updates in this browser. Check your input if the result looks unexpected.
How to use Longest common subsequence calculator
Find the length and one witness for the longest in-order match between two strings. The pre-filled problem gives you a worked starting point. Compare the response with your own working before trying the self-check below.
- Check the example inputs: First string, Second string.
- Change the inputs for your problem. Results update as you type, so finish entering the values before copying an answer.
- Use the working to check an intermediate value or assumption. Then change the example as suggested in the self-check and compare the result.
Supported inputs and limits
Use up to 80 Unicode code points per string. Comparisons distinguish case, whitespace and accented characters.
How it works
A subsequence keeps characters in their original relative order and may skip positions. To be common it must be a subsequence of both inputs. The length of a longest one measures how many characters can be preserved in a matched order across both strings.
The prefix table extends a match from the diagonal when the last characters agree. When they disagree, skipping the last character on one side or the other chooses the better earlier result. Tracing backwards through this table exhibits one sequence of the best length. A tied optimum can have several witnesses.
Example
Run the pre-filled example. Its first result is “Longest common subsequence length: 4”.
- First string
- XMJYAUZ
- Second string
- MZJAWXU
Longest common subsequence length: 4 One sequence: MJAU Characters keep their relative order and can skip positions.
Questions about Longest common subsequence calculator
Can two different strings have multiple longest subsequences?
Yes. An optimal length can have several witnesses, so the displayed example is one of the valid sequences.
Must the characters be adjacent?
No. Adjacent spans are substrings, whereas a subsequence can jump over unchanged or unrelated characters.
Compare ABCDE with ACE.
The length is three and ACE is a witness. It keeps every character from the shorter input in the correct order.
Related tools
Last updated