Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Finding the common streak in two arrays in JavaScript
We are required to write a JavaScript function that takes in two arrays of literals, let's call them arr1 and arr2.
The function should find the longest common streak of literals in the arrays. The function should finally return an array of those literals.
For example ?
If the input arrays are ?
const arr1 = ['a', 'b', 'c', 'd', 'e']; const arr2 = ['k', 'j', 'b', 'c', 'd', 'w'];
Then the output array should be ?
['b', 'c', 'd']
Algorithm Overview
This problem uses dynamic programming to find the Longest Common Subsequence (LCS). The approach involves:
- Converting arrays to strings for character-by-character comparison
- Building a 2D matrix to store LCS lengths
- Backtracking through the matrix to reconstruct the sequence
Implementation
const arr1 = ['a', 'b', 'c', 'd', 'e'];
const arr2 = ['k', 'j', 'b', 'c', 'd', 'w'];
const longestCommonSubsequence = (arr1 = [], arr2 = []) => {
let str1 = arr1.join('');
let str2 = arr2.join('');
// Create 2D array for dynamic programming
const arr = Array(str2.length + 1).fill(null).map(() =>
Array(str1.length + 1).fill(null)
);
// Initialize first row and column with zeros
for (let j = 0; j 0 && i > 0) {
if (str1[j - 1] === str2[i - 1]) {
res.unshift(str1[j - 1]);
j -= 1;
i -= 1;
} else if (arr[i][j] === arr[i][j - 1]) {
j -= 1;
} else {
i -= 1;
}
}
return res;
};
console.log(longestCommonSubsequence(arr1, arr2));
Output
['b', 'c', 'd']
How It Works
The algorithm works in three phases:
- Matrix Building: Creates a 2D matrix where each cell [i][j] represents the length of LCS between the first i characters of str2 and first j characters of str1
- Dynamic Programming: Fills the matrix by comparing characters and taking the maximum LCS length from adjacent cells
- Backtracking: Reconstructs the actual subsequence by tracing back through the matrix
Example with Different Arrays
const arr3 = ['x', 'y', 'z', 'a', 'b']; const arr4 = ['a', 'b', 'x', 'y']; console.log(longestCommonSubsequence(arr3, arr4));
['x', 'y']
Conclusion
This dynamic programming solution efficiently finds the longest common subsequence between two arrays with O(m×n) time complexity. The algorithm is particularly useful for sequence comparison and pattern matching tasks.
Advertisements
