DOJ logoDOJ
Problems
Recently added problemsSaved problemsWorkbooks
CategoriesDLCContestsGroupsTeamsBoard
Ranking
Solved Problem RankingStreak rankingDOJ Power ranking
Status
Call for TasksLoginRegister
DOJ logoDOJ

Community online judge with OI-style subtask scoring, Elo ratings, and Discord account linking.

Problems
ProblemsCategories
Community
ContestsRankingBoardNoticesHost an external contestGuide
Account
LoginRegisterJudge Status
Policy
Terms of ServiceDLC RulesPrivacyAPI documentationLanguage runtimesContest rank rewardsRating and performance
© 2026 DOJ
All rights reserved
Editorial

Longest Common Subsequence

Back to problem

Editorial

For subtask 111, enumerate every subsequence of AAA and check whether it is a subsequence of BBB. This takes O(2N(N+M))O(2^N(N+M))O(2N(N+M)) time.

For the full problem, let Di,jD_{i,j}Di,j​ be the length of a longest common subsequence of the first iii elements of AAA and the first jjj elements of B. Set . If , then . Otherwise, .

Backtrack from DN,MD_{N,M}DN,M​. If the current elements match, add that element to the answer and decrease both indices. Otherwise, move to a preceding state with the same DP value. Reverse the collected elements to obtain an answer. If both preceding states have the same value, either choice works.

The time and space complexity are both O(NM)O(NM)O(NM) per case.

Solution written by GPT6

B
B
D0,j=Di,0=0D_{0,j}=D_{i,0}=0D0,j​=Di,0​=0
Ai=BjA_i=B_jAi​=Bj​
Di,j=Di−1,j−1+1D_{i,j}=D_{i-1,j-1}+1Di,j​=Di−1,j−1​+1
Di,j=max⁡(Di−1,j,Di,j−1)D_{i,j}=\max(D_{i-1,j},D_{i,j-1})Di,j​=max(Di−1,j​,Di,j−1​)