Skip to content

1940. Longest Common Subsequence Between Sorted Arrays 👍

Approach 1: Naive

  • Time: $O(\Sigma |\texttt{arrays[i]}|)$
  • Space: $O(\max(|\texttt{arrays[i]}|))$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  vector<int> longestCommonSubsequence(vector<vector<int>>& arrays) {
    constexpr int kMax = 100;
    vector<int> ans;
    vector<int> count(kMax + 1);

    for (const vector<int>& array : arrays)
      for (const int a : array)
        if (++count[a] == arrays.size())
          ans.push_back(a);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public List<Integer> longestCommonSubsequence(int[][] arrays) {
    final int kMax = 100;
    List<Integer> ans = new ArrayList<>();
    int[] count = new int[kMax + 1];

    for (int[] array : arrays)
      for (final int a : array)
        if (++count[a] == arrays.length)
          ans.add(a);

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def longestCommonSubsequence(self, arrays: list[list[int]]) -> list[int]:
    kMax = 100
    ans = []
    count = [0] * (kMax + 1)

    for array in arrays:
      for a in array:
        count[a] += 1
        if count[a] == len(arrays):
          ans.append(a)

    return ans

Approach 2: Set Intersection

  • Time: $O(\Sigma |\texttt{arrays[i]}|)$
  • Space: $O(\max(|\texttt{arrays[i]}|))$
1
2
3
class Solution:
  def longestCommonSubsequence(self, arrays: list[list[int]]) -> list[int]:
    return sorted(functools.reduce(lambda a, b: set(a) & set(b), arrays))