Longest Common Subsequence Between Sorted Arrays - Problem
Find the Longest Common Subsequence Among Multiple Sorted Arrays

You're given an array of integer arrays arrays where each arrays[i] is sorted in strictly increasing order. Your task is to 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. In this problem, we're looking for elements that appear in all arrays while maintaining their relative order.

Key Points:
• All input arrays are already sorted in strictly increasing order
• The result should contain elements that appear in ALL arrays
• Elements in the result should maintain their original order
• If no common elements exist, return an empty array

Input & Output

example_1.py — Basic Common Elements
$ Input: arrays = [[1,3,4], [1,4,7,9], [1,4]]
Output: [1,4]
💡 Note: Elements 1 and 4 appear in all three arrays. Element 3 appears only in the first array, 7 and 9 only in the second array, so they're not included in the result.
example_2.py — Single Common Element
$ Input: arrays = [[2,3,6,8], [1,2,3,4,5,6], [2,3,4,6,8]]
Output: [2,3,6]
💡 Note: Elements 2, 3, and 6 appear in all arrays. Element 8 appears in first and third arrays but not second. Element 1 and 5 appear only in second array.
example_3.py — No Common Elements
$ Input: arrays = [[1,2,3], [4,5,6], [7,8,9]]
Output: []
💡 Note: No elements appear in all three arrays, so the result is an empty array.

Constraints

  • 1 ≤ arrays.length ≤ 1000
  • 1 ≤ arrays[i].length ≤ 1000
  • 1 ≤ arrays[i][j] ≤ 105
  • arrays[i] is sorted in strictly increasing order

Visualization

Tap to expand
Group AGroup BGroup CAliceBobCharlieCommon Friends: CharlieOnly Charlie appears in all three groups
Understanding the Visualization
1
Count Memberships
Count how many groups each person belongs to
2
Find Universal Members
Keep only those who belong to ALL groups
3
Preserve Order
List them in the order they appear in the first group
Key Takeaway
🎯 Key Insight: Use frequency counting with hash maps to efficiently find elements that appear exactly 'number of arrays' times, then preserve order by iterating through the first array!
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
38.5K Views
Medium Frequency
~15 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen