Longest Common Subsequence Between Sorted Arrays Problem
Description
LeetCode Problem 1940.
Given an array of integer arrays arrays where each arrays[i] is sorted in strictly increasing order, return an integer array representing the longest common subsequence among all the arrays.
A subsequence is a sequence that can be derived from another sequence by deleting some elements (possibly none) without changing the order of the remaining elements.
Example 1:
Input: arrays = [[1,3,4],
[1,4,7,9]]
Output: [1,4]
Explanation: The longest common subsequence in the two arrays is [1,4].
Example 2:
Input: arrays = [[2,3,6,8],
[1,2,3,5,6,7,10],
[2,3,4,6,9]]
Output: [2,3,6]
Explanation: The longest common subsequence in all three arrays is [2,3,6].
Example 3:
Input: arrays = [[1,2,3,4,5],
[6,7,8]]
Output: []
Explanation: There is no common subsequence between the two arrays.
Constraints:
2 <= arrays.length <= 1001 <= arrays[i].length <= 1001 <= arrays[i][j] <= 100arrays[i]is sorted in strictly increasing order.
Solution
Approach: Counting
Every array is strictly increasing, so each value occurs at most once per array. A value belongs to the common subsequence exactly when it appears in all the arrays, that is, when it is counted len(arrays) times in total.
Values are between 1 and 100, so keep a counter array cnt of size 101, count every element of every array, and then list the values from 1 to 100 whose count equals the number of arrays. The result is already increasing.
Complexity: O(M + N) time and O(M) space, where M = 101 is the value range and N is the total number of elements.
class Solution:
def longestCommonSubsequence(self, arrays: List[List[int]]) -> List[int]:
cnt = [0] * 101
for row in arrays:
for x in row:
cnt[x] += 1
return [x for x, v in enumerate(cnt) if v == len(arrays)]