Skip to content

Commit c705bbe

Browse files
committed
Merge pull request kodecocodes#73 from pedrovereza/longest-common-subsequence
Implement Longest Common Subsequence
2 parents a6ddf98 + a544010 commit c705bbe

File tree

10 files changed

+755
-0
lines changed

10 files changed

+755
-0
lines changed

.travis.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,4 @@ script:
2222
- xcodebuild test -project ./Selection\ Sort/Tests/Tests.xcodeproj -scheme Tests
2323
- xcodebuild test -project ./Shell\ Sort/Tests/Tests.xcodeproj -scheme Tests
2424
- xcodebuild test -project ./Stack/Tests/Tests.xcodeproj -scheme Tests
25+
- xcodebuild test -project ./Longest\ Common\ Subsequence/Tests/Tests.xcodeproj -scheme Tests
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
extension String {
2+
func longestCommonSubsequence(other:String) -> String {
3+
4+
func lcsLength(other: String) -> [[Int]] {
5+
var matrix = [[Int]](count:self.characters.count+1, repeatedValue:[Int](count:other.characters.count+1, repeatedValue:0))
6+
7+
for (i, selfChar) in self.characters.enumerate() {
8+
for (j, otherChar) in other.characters.enumerate() {
9+
if (otherChar == selfChar) {
10+
matrix[i+1][j+1] = (matrix[i][j]) + 1
11+
}
12+
else {
13+
matrix[i+1][j+1] = max(matrix[i][j+1], matrix[i+1][j])
14+
}
15+
}
16+
}
17+
18+
return matrix;
19+
}
20+
21+
func backtrack(matrix: [[Int]]) -> String {
22+
var i = self.characters.count
23+
var j = other.characters.count
24+
var charInSequence = self.endIndex
25+
26+
var lcs = String()
27+
28+
while (i >= 1 && j >= 1) {
29+
if (matrix[i][j] == matrix[i][j - 1]) {
30+
j = j - 1
31+
}
32+
else if (matrix[i][j] == matrix[i - 1][j]) {
33+
i = i - 1
34+
charInSequence = charInSequence.predecessor()
35+
}
36+
else {
37+
i = i - 1
38+
j = j - 1
39+
charInSequence = charInSequence.predecessor()
40+
41+
lcs.append(self[charInSequence])
42+
}
43+
}
44+
45+
return String(lcs.characters.reverse());
46+
}
47+
48+
return backtrack(lcsLength(other))
49+
}
50+
}
51+
52+
// Examples
53+
54+
let a = "ABCBX"
55+
let b = "ABDCAB"
56+
let c = "KLMK"
57+
58+
a.longestCommonSubsequence(c) //""
59+
a.longestCommonSubsequence("") //""
60+
a.longestCommonSubsequence(b) //"ABCB"
61+
b.longestCommonSubsequence(a) //"ABCB"
62+
a.longestCommonSubsequence(a) // "ABCBX"
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<Timeline
3+
version = "3.0">
4+
<TimelineItems>
5+
</TimelineItems>
6+
</Timeline>
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
extension String {
2+
func longestCommonSubsequence(other:String) -> String {
3+
4+
// Computes the length of the lcs using dynamic programming
5+
// Output is a matrix of size (n+1)x(m+1), where matrix[x][y] indicates the length
6+
// of lcs between substring (0, x-1) of self and substring (0, y-1) of other.
7+
func lcsLength(other: String) -> [[Int]] {
8+
9+
//Matrix of size (n+1)x(m+1), algorithm needs first row and first column to be filled with 0
10+
var matrix = [[Int]](count:self.characters.count+1, repeatedValue:[Int](count:other.characters.count+1, repeatedValue:0))
11+
12+
for (i, selfChar) in self.characters.enumerate() {
13+
for (j, otherChar) in other.characters.enumerate() {
14+
if (otherChar == selfChar) {
15+
//Common char found, add 1 to highest lcs found so far
16+
matrix[i+1][j+1] = (matrix[i][j]) + 1
17+
}
18+
else {
19+
//Not a match, propagates highest lcs length found so far
20+
matrix[i+1][j+1] = max(matrix[i][j+1], matrix[i+1][j])
21+
}
22+
}
23+
}
24+
25+
//Due to propagation, lcs length is at matrix[n][m]
26+
return matrix;
27+
}
28+
29+
//Backtracks from matrix[n][m] to matrix[1][1] looking for chars that are common to both strings
30+
func backtrack(matrix: [[Int]]) -> String {
31+
var i = self.characters.count
32+
var j = other.characters.count
33+
34+
//charInSequence is in sync with i so we can get self[i]
35+
var charInSequence = self.endIndex
36+
37+
var lcs = String()
38+
39+
while (i >= 1 && j >= 1) {
40+
//Indicates propagation without change, i.e. no new char was added to lcs
41+
if (matrix[i][j] == matrix[i][j - 1]) {
42+
j = j - 1
43+
}
44+
//Indicates propagation without change, i.e. no new char was added to lcs
45+
else if (matrix[i][j] == matrix[i - 1][j]) {
46+
i = i - 1
47+
//As i was subtracted, move back charInSequence
48+
charInSequence = charInSequence.predecessor()
49+
}
50+
//Value on the left and above are different than current cell. This means 1 was added to lcs length (line 16)
51+
else {
52+
i = i - 1
53+
j = j - 1
54+
charInSequence = charInSequence.predecessor()
55+
56+
lcs.append(self[charInSequence])
57+
}
58+
}
59+
60+
//Due to backtrack, chars were added in reverse order: reverse it back.
61+
//Append and reverse is faster than inserting at index 0
62+
return String(lcs.characters.reverse());
63+
}
64+
65+
//Combine dynamic programming approach with backtrack to find the lcs
66+
return backtrack(lcsLength(other))
67+
}
68+
}
Lines changed: 211 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,211 @@
1+
# Longest Common Subsequence
2+
3+
4+
The Longest Common Subsequence (LCS) of two strings is the longest sequence of characters that appear in the same order in both strings. Should not be confused with the Longest Common Substring problem, where characters **must** be a substring of both strings (i.e they have to be immediate neighbours).
5+
6+
One way to find what's the LCS of two strings `a` and `b` is using Dynamic Programming and a backtracking strategy. During the explanation, remember that `n` is the length of `a` and `m` the length of `b`.
7+
8+
## Length of LCS - Dynamic Programming
9+
10+
Dynamic programming is used to determine the length of LCS between all combinations of substrings of `a` and `b`.
11+
12+
13+
```swift
14+
// Computes the length of the lcs using dynamic programming
15+
// Output is a matrix of size (n+1)x(m+1), where matrix[x][y] indicates the length
16+
// of lcs between substring (0, x-1) of self and substring (0, y-1) of other.
17+
func lcsLength(other: String) -> [[Int]] {
18+
19+
//Matrix of size (n+1)x(m+1), algorithm needs first row and first line to be filled with 0
20+
var matrix = [[Int]](count:self.characters.count+1, repeatedValue:[Int](count:other.characters.count+1, repeatedValue:0))
21+
22+
for (i, selfChar) in self.characters.enumerate() {
23+
for (j, otherChar) in other.characters.enumerate() {
24+
if (otherChar == selfChar) {
25+
//Common char found, add 1 to highest lcs found so far
26+
matrix[i+1][j+1] = (matrix[i][j]) + 1
27+
}
28+
else {
29+
//Not a match, propagates highest lcs length found so far
30+
matrix[i+1][j+1] = max(matrix[i][j+1], matrix[i+1][j])
31+
}
32+
}
33+
}
34+
35+
//Due to propagation, lcs length is at matrix[n][m]
36+
return matrix;
37+
}
38+
```
39+
40+
Given strings `"ABCBX"` and `"ABDCAB"` the output matrix of `lcsLength` is the following:
41+
42+
*First row and column added for easier understanding, actual matrix starts on zeros*
43+
44+
```
45+
| | Ø | A | B | D | C | A | B |
46+
| Ø | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
47+
| A | 0 | 1 | 1 | 1 | 1 | 1 | 1 |
48+
| B | 0 | 1 | 2 | 2 | 2 | 2 | 2 |
49+
| C | 0 | 1 | 2 | 2 | 3 | 3 | 3 |
50+
| B | 0 | 1 | 2 | 2 | 3 | 3 | 4 |
51+
| X | 0 | 1 | 2 | 2 | 3 | 3 | 4 |
52+
```
53+
54+
The content of the matrix indicates that position `(i, j)` contains the length of the LCS between substring `(0, i - 1)` of `a` and substring `(0, j - 1)` of `b`.
55+
56+
Example: `(2, 3)` says that the LCS for `"AB"` and `"ABD"` is 2
57+
58+
59+
## Actual LCS - Backtrack
60+
61+
Having the length of every combination makes it possible to determine *which* characters are part of the LCS itself by using a backtracking strategy.
62+
63+
Backtrack starts at matrix[n + 1][m + 1] and *walks* up and left (in this priority) looking for changes that do not indicate a simple propagation. If the number on the left and above are different than the number in the current cell, no propagation happened, it means that `(i, j)` indicates a common char between `a` and `b`, so char at `a[i - 1]` and `b[j - 1]` are part of the LCS and should be stored in the returned value (`self[i - 1]` was used in the code but could be `other[j - 1]`).
64+
65+
```
66+
| | Ø| A| B| D| C| A| B|
67+
| Ø | 0| 0| 0| 0| 0| 0| 0|
68+
| A | 0|↖ 1| 1| 1| 1| 1| 1|
69+
| B | 0| 1|↖ 2|← 2| 2| 2| 2|
70+
| C | 0| 1| 2| 2|↖ 3|← 3| 3|
71+
| B | 0| 1| 2| 2| 3| 3|↖ 4|
72+
| X | 0| 1| 2| 2| 3| 3|↑ 4|
73+
```
74+
Each `` move indicates a character (in row/column header) that is part of the LCS.
75+
76+
One thing to notice is, as it's running backwards, the LCS is built in reverse order. Before returning, the result is reversed to reflect the actual LCS.
77+
78+
79+
80+
```swift
81+
//Backtracks from matrix[n][m] to matrix[1][1] looking for chars that are common to both strings
82+
func backtrack(matrix: [[Int]]) -> String {
83+
var i = self.characters.count
84+
var j = other.characters.count
85+
86+
//charInSequence is in sync with i so we can get self[i]
87+
var charInSequence = self.endIndex
88+
89+
var lcs = String()
90+
91+
while (i >= 1 && j >= 1) {
92+
//Indicates propagation without change, i.e. no new char was added to lcs
93+
if (matrix[i][j] == matrix[i][j - 1]) {
94+
j = j - 1
95+
}
96+
//Indicates propagation without change, i.e. no new char was added to lcs
97+
else if (matrix[i][j] == matrix[i - 1][j]) {
98+
i = i - 1
99+
//As i was subtracted, move back charInSequence
100+
charInSequence = charInSequence.predecessor()
101+
}
102+
//Value on the left and above are different than current cell. This means 1 was added to lcs length (line 16)
103+
else {
104+
i = i - 1
105+
j = j - 1
106+
charInSequence = charInSequence.predecessor()
107+
108+
lcs.append(self[charInSequence])
109+
}
110+
}
111+
112+
//Due to backtrack, chars were added in reverse order: reverse it back.
113+
//Append and reverse is faster than inserting at index 0
114+
return String(lcs.characters.reverse());
115+
}
116+
117+
```
118+
119+
120+
121+
122+
## Putting it all together
123+
124+
125+
```swift
126+
extension String {
127+
func longestCommonSubsequence(other:String) -> String {
128+
129+
// Computes the same of the lcs using dynamic programming
130+
// Output is a matrix of size (n+1)x(m+1), where matrix[x][y] indicates the length
131+
// of lcs between substring (0, x-1) of self and substring (0, y-1) of other.
132+
func lcsLength(other: String) -> [[Int]] {
133+
134+
//Matrix of size (n+1)x(m+1), algorithm needs first row and first line to be filled with 0
135+
var matrix = [[Int]](count:self.characters.count+1, repeatedValue:[Int](count:other.characters.count+1, repeatedValue:0))
136+
137+
for (i, selfChar) in self.characters.enumerate() {
138+
for (j, otherChar) in other.characters.enumerate() {
139+
if (otherChar == selfChar) {
140+
//Common char found, add 1 to highest lcs found so far
141+
matrix[i+1][j+1] = (matrix[i][j]) + 1
142+
}
143+
else {
144+
//Not a match, propagates highest lcs length found so far
145+
matrix[i+1][j+1] = max(matrix[i][j+1], matrix[i+1][j])
146+
}
147+
}
148+
}
149+
150+
//Due to propagation, lcs length is at matrix[n][m]
151+
return matrix;
152+
}
153+
154+
//Backtracks from matrix[n][m] to matrix[1][1] looking for chars that are common to both strings
155+
func backtrack(matrix: [[Int]]) -> String {
156+
var i = self.characters.count
157+
var j = other.characters.count
158+
159+
//charInSequence is in sync with i so we can get self[i]
160+
var charInSequence = self.endIndex
161+
162+
var lcs = String()
163+
164+
while (i >= 1 && j >= 1) {
165+
//Indicates propagation without change, i.e. no new char was added to lcs
166+
if (matrix[i][j] == matrix[i][j - 1]) {
167+
j = j - 1
168+
}
169+
//Indicates propagation without change, i.e. no new char was added to lcs
170+
else if (matrix[i][j] == matrix[i - 1][j]) {
171+
i = i - 1
172+
//As i was subtracted, move back charInSequence
173+
charInSequence = charInSequence.predecessor()
174+
}
175+
//Value on the left and above are different than current cell. This means 1 was added to lcs length (line 16)
176+
else {
177+
i = i - 1
178+
j = j - 1
179+
charInSequence = charInSequence.predecessor()
180+
181+
lcs.append(self[charInSequence])
182+
}
183+
}
184+
185+
//Due to backtrack, chars were added in reverse order: reverse it back.
186+
//Append and reverse is faster than inserting at index 0
187+
return String(lcs.characters.reverse());
188+
}
189+
190+
//Combine dynamic programming approach with backtrack to find the lcs
191+
return backtrack(lcsLength(other))
192+
}
193+
}
194+
```
195+
196+
**Examples:**
197+
198+
```swift
199+
let a = "ABCBX"
200+
let b = "ABDCAB"
201+
let c = "KLMK"
202+
203+
a.longestCommonSubsequence(c) //""
204+
a.longestCommonSubsequence("") //""
205+
a.longestCommonSubsequence(b) //"ABCB"
206+
b.longestCommonSubsequence(a) //"ABCB"
207+
a.longestCommonSubsequence(a) // "ABCBX"
208+
```
209+
210+
211+
*Written for Swift Algorithm Club by Pedro Vereza*
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import Foundation
2+
import XCTest
3+
4+
class LongestCommonSubsquenceTests: XCTestCase {
5+
6+
func testLCSwithSelfIsSelf() {
7+
let a = "ABCDE"
8+
9+
XCTAssertEqual(a, a.longestCommonSubsequence(a))
10+
}
11+
12+
func testLCSWithEmptyStringIsEmptyString() {
13+
let a = "ABCDE"
14+
15+
XCTAssertEqual("", a.longestCommonSubsequence(""))
16+
}
17+
18+
func testLCSIsEmptyWhenNoCharMatches() {
19+
let a = "ABCDE"
20+
let b = "WXYZ"
21+
22+
XCTAssertEqual("", a.longestCommonSubsequence(b))
23+
}
24+
25+
func testLCSIsNotCommutative() {
26+
let a = "ABCDEF"
27+
let b = "XAWDMVBEKD"
28+
29+
XCTAssertEqual("ADE", a.longestCommonSubsequence(b))
30+
XCTAssertEqual("ABD", b.longestCommonSubsequence(a))
31+
}
32+
}

0 commit comments

Comments
 (0)