--- id: 5e6dd1278e6ca105cde40ea9 title: Longest common subsequence challengeType: 5 isHidden: false --- ## Description
The longest common subsequence (or LCS) of groups A and B is the longest group of elements from A and B that are common between the two groups and in the same order in each group. For example, the sequences "1234" and "1224533324" have an LCS of "1234": 1234 1224533324 For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest": thisisatest testing123testing. Your code only needs to deal with strings. For more information on this problem please see Wikipedia.
## Instructions
Write a case-sensitive function that returns the LCS of two strings. You don't need to show multiple LCS's.
## Tests
``` yml tests: - text: lcs should be a function. testString: assert(typeof lcs == 'function'); - text: lcs("thisisatest", "testing123testing") should return a string. testString: assert(typeof lcs("thisisatest", "testing123testing") == 'string'); - text: lcs("thisisatest", "testing123testing") should return "tsitest". testString: assert.equal(lcs("thisisatest", "testing123testing"), "tsitest"); - text: lcs("ABCDGH", "AEDFHR") should return "ADH". testString: assert.equal(lcs("ABCDGH", "AEDFHR"), "ADH"); - text: lcs("AGGTAB", "GXTXAYB") should return "GTAB". testString: assert.equal(lcs("AGGTAB", "GXTXAYB"), "GTAB"); - text: lcs("BDACDB", "BDCB") should return "BDCB". testString: assert.equal(lcs("BDACDB", "BDCB"), "BDCB"); - text: lcs("ABAZDC", "BACBAD") should return "ABAD". testString: assert.equal(lcs("ABAZDC", "BACBAD"), "ABAD"); ```
## Challenge Seed
```js function lcs(a, b) { } ```
## Solution
```js function lcs(a, b) { var aSub = a.substr(0, a.length - 1); var bSub = b.substr(0, b.length - 1); if (a.length === 0 || b.length === 0) { return ''; } else if (a.charAt(a.length - 1) === b.charAt(b.length - 1)) { return lcs(aSub, bSub) + a.charAt(a.length - 1); } else { var x = lcs(a, bSub); var y = lcs(aSub, b); return (x.length > y.length) ? x : y; } } ```