SlideShare a Scribd company logo
1 of 4
Download to read offline
Longest Common Subsequence
The longest common subsequence (LCS) is defined as the longest subsequence that is common to
all the given sequences, provided that the elements of the subsequence are not required to occupy
consecutive positions within the original sequences.
If S1 and S2 are the two given sequences then, Z is the common subsequence
of S1 and S2 if Z is a subsequence of both S1 and S2. Furthermore, Z must be a strictly
increasing sequence of the indices of both S1 and S2.
In a strictly increasing sequence, the indices of the elements chosen from the original sequences
must be in ascending order in Z.
If
S1 = {B, C, D, A, A, C, D}
Then, {A, D, B} cannot be a subsequence of S1 as the order of the elements is not the same (ie.
not strictly increasing sequence).
Let us understand LCS with an example.
If
S1 = {B, C, D, A, A, C, D}
S2 = {A, C, D, B, A, C}
Then, common subsequences are {B, C}, {C, D, A, C}, {D, A, C}, {A, A, C}, {A, C}, {C,
D}, ...
Among these subsequences, {C, D, A, C} is the longest common subsequence.
Let us take two sequences:
The first sequence
Second Sequence
The following steps are followed for finding the longest common subsequence.
1. Create a table of dimension n+1*m+1 where n and m are the lengths of X and Y respectively. The
first row and the first column are filled with zeros.
Initialize a table
2. Fill each cell of the table using the following logic.
3. If the character corresponding to the current row and current column are matching, then fill the
current cell by adding one to the diagonal element. Point an arrow to the diagonal cell.
4. Else take the maximum value from the previous column and previous row element for filling the
current cell. Point an arrow to the cell with maximum value. If they are equal, point to any of them.
Fill the values
5. Step 2 is repeated until the table is filled.
Fill all the values
6. The value in the last row and the last column is the length of the longest common subsequence.
The bottom right corner is the length of the LCS
7. In order to find the longest common subsequence, start from the last element and follow the
direction of the arrow.
Create a path according to the arrows
Thus, the longest common subsequence is CA.
Longest Common Subsequence Algorithm
X and Y be two given sequences
Initialize a table LCS of dimension X.length * Y.length
X.label = X
Y.label = Y
LCS[0][] = 0
LCS[][0] = 0
Start from LCS[1][1]
Compare X[i] and Y[j]
If X[i] = Y[j]
LCS[i][j] = 1 + LCS[i-1, j-1]
Point an arrow to LCS[i][j]
Else
LCS[i][j] = max(LCS[i-1][j], LCS[i][j-1])
Point an arrow to max(LCS[i-1][j], LCS[i][j-1])

More Related Content

What's hot

Geom jeopardy ch 8 review
Geom jeopardy ch 8 reviewGeom jeopardy ch 8 review
Geom jeopardy ch 8 reviewmgneal
 
Chapter 6, triangles For Grade -10
Chapter 6, triangles For Grade -10Chapter 6, triangles For Grade -10
Chapter 6, triangles For Grade -10Siddu Lingesh
 
Forms of the Pythagorean theorem
Forms of the Pythagorean theoremForms of the Pythagorean theorem
Forms of the Pythagorean theoremLucius Sykes, M.A.
 
Geom 3point4and5
Geom 3point4and5Geom 3point4and5
Geom 3point4and5herbison
 
Posiciones de rectas y planos
Posiciones de rectas y planosPosiciones de rectas y planos
Posiciones de rectas y planosssuser72b7e1
 
6 2 Parallelograms
6 2 Parallelograms6 2 Parallelograms
6 2 Parallelogramslmrogers03
 
6 3 Proving Parallelograms
6 3 Proving Parallelograms6 3 Proving Parallelograms
6 3 Proving Parallelogramslmrogers03
 
Homogeneity of an equation
Homogeneity of an equationHomogeneity of an equation
Homogeneity of an equationRosmaya Mokhtar
 
Coordinate geometry 9 grade
Coordinate geometry 9 gradeCoordinate geometry 9 grade
Coordinate geometry 9 gradeSiddu Lingesh
 
Similarity day 1 sss, sas, aa
Similarity day 1  sss, sas, aaSimilarity day 1  sss, sas, aa
Similarity day 1 sss, sas, aajbianco9910
 
How to read log Table
How to read log TableHow to read log Table
How to read log TablePromilabis
 
7 4 Similar Triangles and t-5
7 4 Similar Triangles and t-57 4 Similar Triangles and t-5
7 4 Similar Triangles and t-5lmrogers03
 
Similar Triangles
Similar TrianglesSimilar Triangles
Similar Trianglestaco40
 

What's hot (19)

Geom jeopardy ch 8 review
Geom jeopardy ch 8 reviewGeom jeopardy ch 8 review
Geom jeopardy ch 8 review
 
Chapter 6, triangles For Grade -10
Chapter 6, triangles For Grade -10Chapter 6, triangles For Grade -10
Chapter 6, triangles For Grade -10
 
Forms of the Pythagorean theorem
Forms of the Pythagorean theoremForms of the Pythagorean theorem
Forms of the Pythagorean theorem
 
Geom 3point4and5
Geom 3point4and5Geom 3point4and5
Geom 3point4and5
 
Posiciones de rectas y planos
Posiciones de rectas y planosPosiciones de rectas y planos
Posiciones de rectas y planos
 
6 2 Parallelograms
6 2 Parallelograms6 2 Parallelograms
6 2 Parallelograms
 
7.Congruence of Triangles.pdf
7.Congruence of Triangles.pdf7.Congruence of Triangles.pdf
7.Congruence of Triangles.pdf
 
Similar triangles
Similar trianglesSimilar triangles
Similar triangles
 
6 3 Proving Parallelograms
6 3 Proving Parallelograms6 3 Proving Parallelograms
6 3 Proving Parallelograms
 
Homogeneity of an equation
Homogeneity of an equationHomogeneity of an equation
Homogeneity of an equation
 
Coordinate geometry 9 grade
Coordinate geometry 9 gradeCoordinate geometry 9 grade
Coordinate geometry 9 grade
 
Similarity day 1 sss, sas, aa
Similarity day 1  sss, sas, aaSimilarity day 1  sss, sas, aa
Similarity day 1 sss, sas, aa
 
How to read log Table
How to read log TableHow to read log Table
How to read log Table
 
7 4 Similar Triangles and t-5
7 4 Similar Triangles and t-57 4 Similar Triangles and t-5
7 4 Similar Triangles and t-5
 
Triangles
TrianglesTriangles
Triangles
 
4.3 terms
4.3 terms4.3 terms
4.3 terms
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Similar Triangles
Similar TrianglesSimilar Triangles
Similar Triangles
 
Triangles
Triangles   Triangles
Triangles
 

Similar to Longest common subsequence

Similar to Longest common subsequence (20)

1.1 types of vectors (1)
1.1 types of vectors (1)1.1 types of vectors (1)
1.1 types of vectors (1)
 
Lec25
Lec25Lec25
Lec25
 
(floyd's algm)
(floyd's algm)(floyd's algm)
(floyd's algm)
 
QB104541.pdf
QB104541.pdfQB104541.pdf
QB104541.pdf
 
Ch. 7 electron configuration
Ch. 7 electron configurationCh. 7 electron configuration
Ch. 7 electron configuration
 
Strings.ppt
Strings.pptStrings.ppt
Strings.ppt
 
Unit 1 sem one-SI UNITS AND STATICS
Unit 1 sem one-SI UNITS AND STATICSUnit 1 sem one-SI UNITS AND STATICS
Unit 1 sem one-SI UNITS AND STATICS
 
Warshalls and floyds algorithms
Warshalls and floyds algorithmsWarshalls and floyds algorithms
Warshalls and floyds algorithms
 
Tim Maudlin: New Foundations for Physical Geometry
Tim Maudlin: New Foundations for Physical GeometryTim Maudlin: New Foundations for Physical Geometry
Tim Maudlin: New Foundations for Physical Geometry
 
3D-PPt MODULE 1.pptx
3D-PPt MODULE 1.pptx3D-PPt MODULE 1.pptx
3D-PPt MODULE 1.pptx
 
Gmat quant topic 6 co ordinate geometry solutions
Gmat quant topic 6 co ordinate geometry solutionsGmat quant topic 6 co ordinate geometry solutions
Gmat quant topic 6 co ordinate geometry solutions
 
02 linear algebra
02 linear algebra02 linear algebra
02 linear algebra
 
02 linear algebra
02 linear algebra02 linear algebra
02 linear algebra
 
Control chap7
Control chap7Control chap7
Control chap7
 
Theory of computation
Theory of computationTheory of computation
Theory of computation
 
Stabiltiy & R-H Ccriterion
Stabiltiy & R-H CcriterionStabiltiy & R-H Ccriterion
Stabiltiy & R-H Ccriterion
 
Maths Project 11 class(SETS)
Maths Project 11 class(SETS)Maths Project 11 class(SETS)
Maths Project 11 class(SETS)
 
cupdf.com_control-chap7.ppt
cupdf.com_control-chap7.pptcupdf.com_control-chap7.ppt
cupdf.com_control-chap7.ppt
 
Vector[1]
Vector[1]Vector[1]
Vector[1]
 
A Study on the class of Semirings
A Study on the class of SemiringsA Study on the class of Semirings
A Study on the class of Semirings
 

More from A. S. M. Shafi (20)

2D Transformation in Computer Graphics
2D Transformation in Computer Graphics2D Transformation in Computer Graphics
2D Transformation in Computer Graphics
 
3D Transformation in Computer Graphics
3D Transformation in Computer Graphics3D Transformation in Computer Graphics
3D Transformation in Computer Graphics
 
Projection
ProjectionProjection
Projection
 
2D Transformation
2D Transformation2D Transformation
2D Transformation
 
Line drawing algorithm
Line drawing algorithmLine drawing algorithm
Line drawing algorithm
 
Fragmentation
FragmentationFragmentation
Fragmentation
 
File organization
File organizationFile organization
File organization
 
Bankers algorithm
Bankers algorithmBankers algorithm
Bankers algorithm
 
RR and priority scheduling
RR and priority schedulingRR and priority scheduling
RR and priority scheduling
 
Fcfs and sjf
Fcfs and sjfFcfs and sjf
Fcfs and sjf
 
Applications of stack
Applications of stackApplications of stack
Applications of stack
 
1D Array
1D Array1D Array
1D Array
 
2D array
2D array2D array
2D array
 
Stack push pop
Stack push popStack push pop
Stack push pop
 
Queue
QueueQueue
Queue
 
Searching
SearchingSearching
Searching
 
Sorting
SortingSorting
Sorting
 
Linked list
Linked listLinked list
Linked list
 
Sum of subset problem
Sum of subset problemSum of subset problem
Sum of subset problem
 
Quick sort
Quick sortQuick sort
Quick sort
 

Recently uploaded

OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsSandeep D Chaudhary
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesAmanpreetKaur157993
 
PSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxPSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxMarlene Maheu
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptNishitharanjan Rout
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....Ritu480198
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaEADTU
 
How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17Celine George
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code ExamplesPeter Brusilovsky
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...Nguyen Thanh Tu Collection
 
Trauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical PrinciplesTrauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical PrinciplesPooky Knightsmith
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...Nguyen Thanh Tu Collection
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17Celine George
 
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportBasic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportDenish Jangid
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSAnaAcapella
 
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxAnalyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxLimon Prince
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppCeline George
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...Gary Wood
 

Recently uploaded (20)

OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategies
 
PSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxPSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptx
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
Supporting Newcomer Multilingual Learners
Supporting Newcomer  Multilingual LearnersSupporting Newcomer  Multilingual Learners
Supporting Newcomer Multilingual Learners
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
 
How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code Examples
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
 
Trauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical PrinciplesTrauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical Principles
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportBasic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxAnalyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge App
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 

Longest common subsequence

  • 1. Longest Common Subsequence The longest common subsequence (LCS) is defined as the longest subsequence that is common to all the given sequences, provided that the elements of the subsequence are not required to occupy consecutive positions within the original sequences. If S1 and S2 are the two given sequences then, Z is the common subsequence of S1 and S2 if Z is a subsequence of both S1 and S2. Furthermore, Z must be a strictly increasing sequence of the indices of both S1 and S2. In a strictly increasing sequence, the indices of the elements chosen from the original sequences must be in ascending order in Z. If S1 = {B, C, D, A, A, C, D} Then, {A, D, B} cannot be a subsequence of S1 as the order of the elements is not the same (ie. not strictly increasing sequence). Let us understand LCS with an example. If S1 = {B, C, D, A, A, C, D} S2 = {A, C, D, B, A, C} Then, common subsequences are {B, C}, {C, D, A, C}, {D, A, C}, {A, A, C}, {A, C}, {C, D}, ... Among these subsequences, {C, D, A, C} is the longest common subsequence.
  • 2. Let us take two sequences: The first sequence Second Sequence The following steps are followed for finding the longest common subsequence. 1. Create a table of dimension n+1*m+1 where n and m are the lengths of X and Y respectively. The first row and the first column are filled with zeros. Initialize a table 2. Fill each cell of the table using the following logic. 3. If the character corresponding to the current row and current column are matching, then fill the current cell by adding one to the diagonal element. Point an arrow to the diagonal cell. 4. Else take the maximum value from the previous column and previous row element for filling the current cell. Point an arrow to the cell with maximum value. If they are equal, point to any of them.
  • 3. Fill the values 5. Step 2 is repeated until the table is filled. Fill all the values 6. The value in the last row and the last column is the length of the longest common subsequence. The bottom right corner is the length of the LCS
  • 4. 7. In order to find the longest common subsequence, start from the last element and follow the direction of the arrow. Create a path according to the arrows Thus, the longest common subsequence is CA. Longest Common Subsequence Algorithm X and Y be two given sequences Initialize a table LCS of dimension X.length * Y.length X.label = X Y.label = Y LCS[0][] = 0 LCS[][0] = 0 Start from LCS[1][1] Compare X[i] and Y[j] If X[i] = Y[j] LCS[i][j] = 1 + LCS[i-1, j-1] Point an arrow to LCS[i][j] Else LCS[i][j] = max(LCS[i-1][j], LCS[i][j-1]) Point an arrow to max(LCS[i-1][j], LCS[i][j-1])