CS 170
Algorithms
Fall 2014
David Wagner
Sol 8
1. (20 pts.)
Subsequence
Design an efficient algorithm to check whether the string
A
[
1
..
n
]
is a subsequence of
B
[
1
..
m
]
, for
n
≤
m
. The
running time of your solution should be at most
O
(
nm
)
.
Note: the elements in a subsequence do not need to be consecutive (subsequence
6
=
substring).
Solution 1
: We can solve this problem with dynamic programming. Define the predicate
f
(
i
,
j
)
to be true if
the string
A
[
1
...
i
]
is a subsequence of
B
[
1
...
j
]
. We obtain a recursive formula for
f
(
i
,
j
)
:
f
(
i
,
j
) =
True
if
i
=
0
∧
j
≥
0
False
if
j
<
i
f
(
i

1
,
j

1
)
if
A
[
i
] =
B
[
j
]
f
(
i
,
j

1
)
otherwise
Pseudocode:
1.
For
j
:
=
0
,
1
,...,
m
:
2.
Set
f
[
0
][
j
]
:
=
True.
3.
For
i
:
=
1
,
2
,...,
n
:
4.
For
j
:
=
1
,
2
,...,
m
:
5.
If
j
<
i
:
6.
Set
f
[
i
][
j
] =
False.
7.
else if
A
[
i
] =
B
[
j
]
:
8.
Set
f
[
i
][
j
]
:
=
f
[
i

1
][
j

1
]
.
7.
else:
8.
Set
f
[
i
][
j
]
:
=
f
[
i
][
j

1
]
.
9.
Return
f
(
n
,
m
)
.
Correctness:
The recursive expression for
f
(
i
,
j
)
follows from a case analysis:
• if
A
[
i
] =
B
[
j
]
: Since
B
[
j
]
matches with
A
[
i
]
,
A
[
1
...
i
]
is a subsequence of
B
[
1
...
j
] iff
A
[
1
...
i

1
]
is a
subsequence of
B
[
1
...
j

1
]
.
• if
A
[
i
]
6
=
B
[
j
]
: Since
B
[
j
]
doesn’t match with
A
[
i
]
,
A
[
1
...
i
]
is a subsequence of
B
[
1
...
j
] iff
A
[
1
...
i
]
is
a subsequence of
B
[
1
...
j

1
]
.
We justify the base cases as follows:
•
i
=
0
∧
j
≥
0: There are no remaining characters within
A
to match with
B
.
A
[
1
...
0
]
is trivially a
subsequence of
B
[
1
...
j
]
. Therefore,
f
(
i
,
j
)
is True.
•
j
<
i
: Since
A
[
1
...
i
]
is a larger string than
B
[
1
...
j
]
,
A
[
1
...
i
]
cannot be a subsequence of
B
[
1
...
j
]
.
Therefore,
f
(
i
,
j
)
is False.
CS 170, Fall 2014, Sol 8
1