Longest Common Subsequence of two arrays out of which one array consists of distinct elements only | Function to find the longest Common Subsequence between the two arrays ; Maps elements of firstArr [ ] to their respective indices ; Traverse the array firstArr [ ] ; Stores the indices of common elements between firstArr [ ] and secondArr [ ] ; Traverse the array secondArr [ ] ; If current element exists in the Map ; Stores lIS from tempArr [ ] ; Driver Code
function LCS ( firstArr , secondArr ) { let mp = new Map ( ) for ( let i = 0 ; i < firstArr . length ; i ++ ) { mp . set ( firstArr [ i ] , i + 1 ) ; } let tempArr = [ ] ; for ( let i = 0 ; i < secondArr . length ; i ++ ) { if ( mp . has ( secondArr [ i ] ) ) { tempArr . push ( mp . get ( secondArr [ i ] ) ) ; } } let tail = [ ] ; tail . push ( tempArr [ 0 ] ) ; for ( let i = 1 ; i < tempArr . length ; i ++ ) { if ( tempArr [ i ] > tail [ tail . length - 1 ] ) tail . push ( tempArr [ i ] ) ; else if ( tempArr [ i ] < tail [ 0 ] ) tail . unshift ( 0 , tempArr [ i ] ) ; } return tail . length ; } let firstArr = [ 3 , 5 , 1 , 8 ] ; let secondArr = [ 3 , 3 , 5 , 3 , 8 ] ; document . write ( LCS ( firstArr , secondArr ) ) ;