VOOZH about

URL: https://www.geeksforgeeks.org/dsa/length-of-longest-common-prime-subsequence-from-two-given-arrays/

⇱ Length of longest common prime subsequence from two given arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Length of longest common prime subsequence from two given arrays

Last Updated : 15 Jul, 2025

Given two arrays arr1[] and arr2[] of length N and M respectively, the task is to find the length of the longest common prime subsequence that can be obtained from the two given arrays.

Examples: 

Input: arr1[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}, arr2[] = {2, 5, 6, 3, 7, 9, 8} 
Output:
Explanation: 
The longest common prime subsequence present in both the arrays is {2, 3, 5, 7}.

Input: arr1[] = {1, 3, 5, 7, 9}, arr2[] = {2, 4, 6, 8, 10} 
Output:
Explanation: 
In the above arrays, the prime subsequence of arr1[] is {1, 3, 5, 7} and arr2[] is {2}. Therefore, there is no common prime numbers which are present in both the arrays. Hence, the result is 0.

Naive Approach: The simplest idea is to consider all subsequences of arr1[] and check if all numbers in this subsequence are prime and appear in arr2[]. Then find the longest length of these subsequences.

Time Complexity: O(M * 2N
Auxiliary Space: O(N)

Efficient Approach: The idea is to find all the prime numbers from both the arrays and then find the longest common prime subsequence from them using Dynamic Programming. Follow the steps below to solve the problem: 

  1. Find all the prime numbers between the minimum element of the array and maximum element of the array using Sieve Of Eratosthenes algorithm.
  2. Store the sequence of primes from the arrays arr1[] and arr2[].
  3. Find the LCS of the two sequences of primes.

Below is the implementation of the above approach:


Output
4

Time Complexity: O(N * M) 
Auxiliary Space: O(N * M)

Comment