Longest subsequence such that adjacent elements have at least one common digit

Given an array arr[] of N integers, the task is to find the length of the longest sub-sequence such that adjacent elements of the sub-sequence have at least one digit in common.
Examples:Â
Â
Input: arr[] = {1, 12, 44, 29, 33, 96, 89}Â
Output: 5Â
The longest sub-sequence is {1 12 29 96 89}
Input: arr[] = {12, 23, 45, 43, 36, 97}Â
Output: 4Â
The longest sub-sequence is {12 23 43 36}Â
Â
Â
Approach: The idea is to store the length of longest sub-sequence for each digit present in an element of the array.Â
Â
- dp[i][d] represents the length of the longest sub-sequence up to ith element if digit d is the common digit.
- Declare a cnt array and set cnt[d] = 1 for each digit present in current element.
- Consider each digit d as common digit and find maximum length sub-sequence ending at arr[i] as dp[i][d] = max(dp[j][d]+1) (0<=j<i).
- Also find a local maximum max(dp[i][d]) for current element.
- After finding local maximum update dp[i][d] for all digits present in the current element to a local maximum.
- This is required as local maximum represents maximum length sub-sequence for an element having digit d.
E.g. Consider arr[] = {24, 49, 96}.Â
The local maximum for 49 is 2 obtain from digit 4.Â
This local maximum will be used in finding the local maximum for 96 with common digit 9.Â
For that it is required for all digits in 49, dp[i][d] should be set to local maximum.
Below is the implementation of the above approach:Â
C++
// C++ program to find maximum length subsequence// such that adjacent elements have at least// one common digit#include <bits/stdc++.h>using namespace std;Â
// Returns length of maximum length subsequenceint findSubsequence(int arr[], int n){Â
    // To store the length of the    // maximum length subsequence    int len = 1;Â
    // To store current element arr[i]    int tmp;Â
    int i, j, d;Â
    // To store the length of the sub-sequence    // ending at index i and having common digit d    int dp[n][10];Â
    memset(dp, 0, sizeof(dp));Â
    // To store digits present in current element    int cnt[10];Â
    // To store length of maximum length subsequence    // ending at index i    int locMax;Â
    // For first element maximum length is 1 for    // each digit    tmp = arr[0];    while (tmp > 0) {        dp[0][tmp % 10] = 1;        tmp /= 10;    }Â
    // Find digits of each element, then find length    // of subsequence for each digit and then find    // local maximum    for (i = 1; i < n; i++) {        tmp = arr[i];        locMax = 1;        memset(cnt, 0, sizeof(cnt));Â
        // Find digits in current element        while (tmp > 0) {            cnt[tmp % 10] = 1;            tmp /= 10;        }Â
        // For each digit present find length of        // subsequence and find local maximum        for (d = 0; d <= 9; d++) {            if (cnt[d]) {                dp[i][d] = 1;                for (j = 0; j < i; j++) {                    dp[i][d] = max(dp[i][d], dp[j][d] + 1);                    locMax = max(dp[i][d], locMax);                }            }        }Â
        // Update value of dp[i][d] for each digit        // present in current element to local maximum        // found.        for (d = 0; d <= 9; d++) {            if (cnt[d]) {                dp[i][d] = locMax;            }        }Â
        // Update maximum length with local maximum        len = max(len, locMax);    }Â
    return len;}Â
// Driver codeint main(){Â Â Â Â int arr[] = { 1, 12, 44, 29, 33, 96, 89 };Â Â Â Â int n = sizeof(arr) / sizeof(arr[0]);Â
    cout << findSubsequence(arr, n);Â
    return 0;} |
Java
// Java program to find maximum length subsequence// such that adjacent elements have at least// one common digitÂ
class GFG{Â
// Returns length of maximum length subsequencestatic int findSubsequence(int arr[], int n){Â
    // To store the length of the    // maximum length subsequence    int len = 1;Â
    // To store current element arr[i]    int tmp;Â
    int i, j, d;Â
    // To store the length of the sub-sequence    // ending at index i and having common digit d    int[][] dp = new int[n][10];Â
Â
    // To store digits present in current element    int[] cnt = new int[10];Â
    // To store length of maximum length subsequence    // ending at index i    int locMax;Â
    // For first element maximum length is 1 for    // each digit    tmp = arr[0];    while (tmp > 0)     {        dp[0][tmp % 10] = 1;        tmp /= 10;    }Â
    // Find digits of each element, then find length    // of subsequence for each digit and then find    // local maximum    for (i = 1; i < n; i++)     {        tmp = arr[i];        locMax = 1;        for (int x = 0; x < 10; x++)        cnt[x]=0;Â
        // Find digits in current element        while (tmp > 0)         {            cnt[tmp % 10] = 1;            tmp /= 10;        }Â
        // For each digit present find length of        // subsequence and find local maximum        for (d = 0; d <= 9; d++)        {            if (cnt[d] > 0)            {                dp[i][d] = 1;                for (j = 0; j < i; j++)                 {                    dp[i][d] = Math.max(dp[i][d], dp[j][d] + 1);                    locMax = Math.max(dp[i][d], locMax);                }            }        }Â
        // Update value of dp[i][d] for each digit        // present in current element to local maximum        // found.        for (d = 0; d <= 9; d++)        {            if (cnt[d] > 0)            {                dp[i][d] = locMax;            }        }Â
        // Update maximum length with local maximum        len = Math.max(len, locMax);    }Â
    return len;}Â
// Driver codepublic static void main (String[] args) {Â Â Â Â int arr[] = { 1, 12, 44, 29, 33, 96, 89 };Â Â Â Â int n = arr.length;Â
    System.out.println(findSubsequence(arr, n));}}Â
// This code is contributed by mits |
Python3
# Python3 program to find maximum # Length subsequence such that # adjacent elements have at least# one common digitÂ
# Returns Length of maximum # Length subsequencedef findSubsequence(arr, n):Â
    # To store the Length of the    # maximum Length subsequence    Len = 1Â
    # To store current element arr[i]    tmp = 0Â
    i, j, d = 0, 0, 0Â
    # To store the Length of the sub-sequence    # ending at index i and having common digit d    dp = [[0 for i in range(10)]              for i in range(n)]Â
    # To store digits present in current element    cnt = [0 for i in range(10)]Â
    # To store Length of maximum     # Length subsequence ending at index i    locMax = 0Â
    # For first element maximum     # Length is 1 for each digit    tmp = arr[0]    while (tmp > 0):        dp[0][tmp % 10] = 1        tmp //= 10Â
    # Find digits of each element,     # then find Length of subsequence     # for each digit and then find    # local maximum    for i in range(1, n):        tmp = arr[i]        locMax = 1        cnt = [0 for i in range(10)]Â
        # Find digits in current element        while (tmp > 0):            cnt[tmp % 10] = 1            tmp //= 10Â
        # For each digit present find Length of        # subsequence and find local maximum        for d in range(10):            if (cnt[d]):                dp[i][d] = 1                for j in range(i):                    dp[i][d] = max(dp[i][d],                                    dp[j][d] + 1)                    locMax = max(dp[i][d], locMax)Â
        # Update value of dp[i][d] for each digit        # present in current element to local         # maximum found.        for d in range(10):            if (cnt[d]):                dp[i][d] = locMaxÂ
        # Update maximum Length         # with local maximum        Len = max(Len, locMax)    return LenÂ
# Driver codearr = [1, 12, 44, 29, 33, 96, 89]n = len(arr)Â
print(findSubsequence(arr, n))Â
# This code is contributed # by mohit kumar |
C#
// C# program to find maximum length subsequence// such that adjacent elements have at least// one common digitusing System;Â
class GFG{Â
// Returns length of maximum length subsequencestatic int findSubsequence(int []arr, int n){Â
    // To store the length of the    // maximum length subsequence    int len = 1;Â
    // To store current element arr[i]    int tmp;Â
    int i, j, d;Â
    // To store the length of the sub-sequence    // ending at index i and having common digit d    int[,] dp = new int[n, 10];Â
Â
    // To store digits present in current element    int[] cnt = new int[10];Â
    // To store length of maximum length subsequence    // ending at index i    int locMax;Â
    // For first element maximum length is 1 for    // each digit    tmp = arr[0];    while (tmp > 0)     {        dp[0, tmp % 10] = 1;        tmp /= 10;    }Â
    // Find digits of each element, then find length    // of subsequence for each digit and then find    // local maximum    for (i = 1; i < n; i++)     {        tmp = arr[i];        locMax = 1;        for (int x = 0; x < 10; x++)            cnt[x] = 0;Â
        // Find digits in current element        while (tmp > 0)         {            cnt[tmp % 10] = 1;            tmp /= 10;        }Â
        // For each digit present find length of        // subsequence and find local maximum        for (d = 0; d <= 9; d++)        {            if (cnt[d] > 0)            {                dp[i, d] = 1;                for (j = 0; j < i; j++)                 {                    dp[i, d] = Math.Max(dp[i, d], dp[j, d] + 1);                    locMax = Math.Max(dp[i, d], locMax);                }            }        }Â
        // Update value of dp[i,d] for each digit        // present in current element to local maximum        // found.        for (d = 0; d <= 9; d++)        {            if (cnt[d] > 0)            {                dp[i, d] = locMax;            }        }Â
        // Update maximum length with local maximum        len = Math.Max(len, locMax);    }Â
    return len;}Â
// Driver codepublic static void Main() {Â Â Â Â int []arr = { 1, 12, 44, 29, 33, 96, 89 };Â Â Â Â int n = arr.Length;Â
    Console.WriteLine(findSubsequence(arr, n));}}Â
// This code is contributed by mits |
Javascript
<script>// Javascript program to find maximum length subsequence// such that adjacent elements have at least// one common digitÂ
// Returns length of maximum length subsequencefunction findSubsequence(arr,n){Â
    // To store the length of the    // maximum length subsequence    let len = 1;       // To store current element arr[i]    let tmp;       let i, j, d;       // To store the length of the sub-sequence    // ending at index i and having common digit d    let dp = new Array(n);    for(let i = 0; i < n; i++)    {        dp[i] = new Array(10);        for(let j = 0; j < 10; j++)        {            dp[i][j] = 0;        }    }          // To store digits present in current element    let cnt = new Array(10);       // To store length of maximum length subsequence    // ending at index i    let locMax;       // For first element maximum length is 1 for    // each digit    tmp = arr[0];    while (tmp > 0)     {        dp[0][tmp % 10] = 1;        tmp = Math.floor(tmp/10);    }       // Find digits of each element, then find length    // of subsequence for each digit and then find    // local maximum    for (i = 1; i < n; i++)     {        tmp = arr[i];        locMax = 1;        for (let x = 0; x < 10; x++)            cnt[x]=0;           // Find digits in current element        while (tmp > 0)         {            cnt[tmp % 10] = 1;            tmp = Math.floor(tmp/10);        }           // For each digit present find length of        // subsequence and find local maximum        for (d = 0; d <= 9; d++)        {            if (cnt[d] > 0)            {                dp[i][d] = 1;                for (j = 0; j < i; j++)                 {                    dp[i][d] = Math.max(dp[i][d], dp[j][d] + 1);                    locMax = Math.max(dp[i][d], locMax);                }            }        }           // Update value of dp[i][d] for each digit        // present in current element to local maximum        // found.        for (d = 0; d <= 9; d++)        {            if (cnt[d] > 0)            {                dp[i][d] = locMax;            }        }           // Update maximum length with local maximum        len = Math.max(len, locMax);    }       return len;}Â
// Driver codelet arr=[ 1, 12, 44, 29, 33, 96, 89];let n = arr.length;document.write(findSubsequence(arr, n));Â Â Â Â Â Â Â Â Â // This code is contributed by rag2127</script> |
5
Time Complexity: O(n2)Â
Auxiliary Space: O(n)
The auxiliary space required for above solution can be further reduced. Observe that for each digit d present in arr[i], it is required to find maximum length sub-sequence upto that digit irrespective of the fact that at which element the sub-sequence end. This reduces auxiliary space required to O(1). For each arr[i], find local maximum and update dig[d] for each digit d in arr[i] to local maximum.Â
Below is the implementation of the above approach:Â
Â
C++
// C++ program to find maximum length subsequence// such that adjacent elements have at least// one common digit#include <bits/stdc++.h>using namespace std;Â
// Returns length of maximum length subsequenceint findSubsequence(int arr[], int n){Â
    // To store length of maximum length subsequence    int len = 1;Â
    // To store current element arr[i]    int tmp;Â
    int i, j, d;Â
    // To store length of subsequence    // having common digit d    int dp[10];Â
    memset(dp, 0, sizeof(dp));Â
    // To store digits present in current element    int cnt[10];Â
    // To store local maximum for current element    int locMax;Â
    // For first element maximum length is 1 for    // each digit    tmp = arr[0];    while (tmp > 0) {        dp[tmp % 10] = 1;        tmp /= 10;    }Â
    // Find digits of each element, then find length    // of subsequence for each digit and then find    // local maximum    for (i = 1; i < n; i++) {        tmp = arr[i];        locMax = 1;        memset(cnt, 0, sizeof(cnt));Â
        // Find digits in current element        while (tmp > 0) {            cnt[tmp % 10] = 1;            tmp /= 10;        }Â
        // For each digit present find length of        // subsequence and find local maximum        for (d = 0; d <= 9; d++) {            if (cnt[d]) {                dp[d]++;                locMax = max(locMax, dp[d]);            }        }Â
        // Update value of dp[d] for each digit        // present in current element to local maximum        // found        for (d = 0; d <= 9; d++) {            if (cnt[d]) {                dp[d] = locMax;            }        }Â
        // Update maximum length with local maximum        len = max(len, locMax);    }Â
    return len;}Â
// Driver codeint main(){Â Â Â Â int arr[] = { 1, 12, 44, 29, 33, 96, 89 };Â Â Â Â int n = sizeof(arr) / sizeof(arr[0]);Â
    cout << findSubsequence(arr, n);Â
    return 0;} |
Java
// Java program to find maximum length subsequence // such that adjacent elements have at least // one common digit import java.util.*;Â
class GFG {Â
// Returns length of maximum length subsequence static int findSubsequence(int arr[], int n) { Â
    // To store length of maximum length subsequence     int len = 1; Â
    // To store current element arr[i]     int tmp; Â
    int i, j, d; Â
    // To store length of subsequence     // having common digit d     int dp[] = new int[10]; Â
Â
    // To store digits present in current element     int cnt[] = new int[10]; Â
    // To store local maximum for current element     int locMax; Â
    // For first element maximum length is 1 for     // each digit     tmp = arr[0];     while (tmp > 0)     {         dp[tmp % 10] = 1;         tmp /= 10;     } Â
    // Find digits of each element, then find length     // of subsequence for each digit and then find     // local maximum     for (i = 1; i < n; i++)     {         tmp = arr[i];         locMax = 1;                 Arrays.fill(cnt, 0);Â
        // Find digits in current element         while (tmp > 0)         {             cnt[tmp % 10] = 1;             tmp /= 10;         } Â
        // For each digit present find length of         // subsequence and find local maximum         for (d = 0; d <= 9; d++)         {             if (cnt[d] == 1)             {                 dp[d]++;                 locMax = Math.max(locMax, dp[d]);             }         } Â
        // Update value of dp[d] for each digit         // present in current element to local maximum         // found         for (d = 0; d <= 9; d++)         {             if (cnt[d] == 1)             {                 dp[d] = locMax;             }         } Â
        // Update maximum length with local maximum         len = Math.max(len, locMax);     } Â
    return len; } Â
// Driver code public static void main(String[] args) {Â Â Â Â int arr[] = { 1, 12, 44, 29, 33, 96, 89 }; Â Â Â Â int n = arr.length; Â Â Â Â Â Â Â Â System.out.print(findSubsequence(arr, n)); }}Â
/* This code contributed by PrinciRaj1992 */ |
Python3
# Python3 program to find maximum length# subsequence such that adjacent elements # have at least one common digit Â
# Returns length of maximum# length subsequence def findSubsequence(arr, n) :Â
    # To store length of maximum     # length subsequence     length = 1; Â
    # To store length of subsequence     # having common digit d     dp = [0] * 10; Â
    # For first element maximum length    # is 1 for each digit     tmp = arr[0];     while (tmp > 0) :         dp[tmp % 10] = 1;         tmp //= 10;      Â
    # Find digits of each element, then    # find length of subsequence for each     # digit and then find local maximum     for i in range(1, n) :        tmp = arr[i];         locMax = 1;        cnt = [0] * 10                 # Find digits in current element         while (tmp > 0) :            cnt[tmp % 10] = 1;             tmp //= 10; Â
        # For each digit present find length of         # subsequence and find local maximum         for d in range(10) :             if (cnt[d]) :                 dp[d] += 1;                 locMax = max(locMax, dp[d]); Â
        # Update value of dp[d] for each digit         # present in current element to local         # maximum found         for d in range(10) :             if (cnt[d]) :                dp[d] = locMax;              # Update maximum length with local         # maximum         length = max(length, locMax); Â
    return length; Â
# Driver code if __name__ == "__main__" :Â Â Â Â arr = [ 1, 12, 44, 29, 33, 96, 89 ]; Â Â Â Â n = len(arr)Â
    print(findSubsequence(arr, n));     # This code is contributed by Ryuga |
C#
// C# program to find maximum length subsequence // such that adjacent elements have at least // one common digit using System;Â
class GFG {Â
// Returns length of maximum length subsequence static int findSubsequence(int []arr, int n) { Â
    // To store length of maximum length subsequence     int len = 1; Â
    // To store current element arr[i]     int tmp; Â
    int i, j, d; Â
    // To store length of subsequence     // having common digit d     int []dp = new int[10]; Â
Â
    // To store digits present in current element     int []cnt = new int[10]; Â
    // To store local maximum for current element     int locMax; Â
    // For first element maximum length is 1 for     // each digit     tmp = arr[0];     while (tmp > 0)     {         dp[tmp % 10] = 1;         tmp /= 10;     } Â
    // Find digits of each element, then find length     // of subsequence for each digit and then find     // local maximum     for (i = 1; i < n; i++)     {         tmp = arr[i];         locMax = 1;         for(int k = 0; k < 10; k++)        {            cnt[k] = 0;        }        // Find digits in current element         while (tmp > 0)         {             cnt[tmp % 10] = 1;             tmp /= 10;         } Â
        // For each digit present find length of         // subsequence and find local maximum         for (d = 0; d <= 9; d++)         {             if (cnt[d] == 1)             {                 dp[d]++;                 locMax = Math.Max(locMax, dp[d]);             }         } Â
        // Update value of dp[d] for each digit         // present in current element to local maximum         // found         for (d = 0; d <= 9; d++)         {             if (cnt[d] == 1)             {                 dp[d] = locMax;             }         } Â
        // Update maximum length with local maximum         len = Math.Max(len, locMax);     } Â
    return len; } Â
// Driver code public static void Main(String[] args) {Â Â Â Â int []arr = { 1, 12, 44, 29, 33, 96, 89 }; Â Â Â Â int n = arr.Length; Â Â Â Â Â Â Â Â Console.WriteLine(findSubsequence(arr, n)); }}Â
// This code contributed by Rajput-Ji |
Javascript
<script>Â
// JavaScript program to find maximum length subsequence // such that adjacent elements have at least // one common digit Â
    // Returns length of maximum length subsequence    function findSubsequence(arr , n) {Â
        // To store length of maximum length subsequence        var len = 1;Â
        // To store current element arr[i]        var tmp;Â
        var i, j, d;Â
        // To store length of subsequence        // having common digit d        var dp = Array(10).fill(0);Â
        // To store digits present in current element        var cnt = Array(10).fill(0);Â
        // To store local maximum for current element        var locMax;Â
        // For first element maximum length is 1 for        // each digit        tmp = arr[0];        while (tmp > 0) {            dp[tmp % 10] = 1;            tmp = parseInt(tmp/10);        }Â
        // Find digits of each element, then find length        // of subsequence for each digit and then find        // local maximum        for (var i = 1; i < n; i++) {            tmp = arr[i];            locMax = 1;            cnt.fill( 0);Â
            // Find digits in current element            while (tmp > 0) {                cnt[tmp % 10] = 1;                tmp = parseInt(tmp/10);            }Â
            // For each digit present find length of            // subsequence and find local maximum            for (d = 0; d <= 9; d++) {                if (cnt[d] == 1) {                    dp[d]++;                    locMax = Math.max(locMax, dp[d]);                }            }Â
            // Update value of dp[d] for each digit            // present in current element to local maximum            // found            for (d = 0; d <= 9; d++) {                if (cnt[d] == 1) {                    dp[d] = locMax;                }            }Â
            // Update maximum length with local maximum            len = Math.max(len, locMax);        }Â
        return len;    }Â
    // Driver code             var arr = [ 1, 12, 44, 29, 33, 96, 89 ];        var n = arr.length;        document.write(findSubsequence(arr, n));Â
// This code contributed by gauravrajput1Â
</script> |
PHP
<?php// PHP program to find maximum length subsequence// such that adjacent elements have at least// one common digitÂ
// Returns length of maximum length subsequencefunction findSubsequence($arr, $n){Â
    // To store length of maximum length    // subsequence    $len = 1;Â
    // To store length of subsequence    // having common digit d    $dp = array_fill(0, 10, NULL);Â
    // For first element maximum length is 1     // for each digit    $tmp = $arr[0];    while ($tmp > 0)    {        $dp[$tmp % 10] = 1;        $tmp = intval($tmp / 10);    }Â
    // Find digits of each element, then     // find length of subsequence for each     // digit and then find local maximum    for ($i = 1; $i < $n; $i++)    {        $tmp = $arr[$i];        $locMax = 1;        $cnt = array_fill(0, 10, NULL);                 // Find digits in current element        while ($tmp > 0)         {            $cnt[$tmp % 10] = 1;            $tmp = intval($tmp / 10);        }Â
        // For each digit present find length of        // subsequence and find local maximum        for ($d = 0; $d <= 9; $d++)        {            if ($cnt[$d])             {                $dp[$d]++;                $locMax = max($locMax, $dp[$d]);            }        }Â
        // Update value of dp[d] for each digit        // present in current element to local         // maximum found        for ($d = 0; $d <= 9; $d++)        {            if ($cnt[$d])             {                $dp[$d] = $locMax;            }        }Â
        // Update maximum length with        // local maximum        $len = max($len, $locMax);    }Â
    return $len;}Â
// Driver code$arr = array( 1, 12, 44, 29, 33, 96, 89 );$n = sizeof($arr);echo findSubsequence($arr, $n);Â
// This code is contributed by ita_c?> |
5
Time Complexity: O(n)Â
Auxiliary Space: O(1)
Â
Using Brute Force:
Approach:
We can generate all possible sub-sequences of the given sequence and check if any adjacent elements have at least one common digit 3. We can then return the length of the longest sub-sequence that satisfies this condition.
Define a function has_common_digit(a, b) that takes two integers a and b as input and returns True if they have at least one digit in common, otherwise False.
Define a function longest_subsequence(arr) that takes a list of integers arr as input and returns the length of the longest subsequence of arr such that adjacent elements have at least one common digit.
Initialize a variable max_len to 0, which will store the length of the longest subsequence found so far.
Generate all possible subsequences of arr using a binary representation of integers from 0 to 2^n – 1, where n is the length of arr. Each bit in the binary representation represents the presence or absence of the corresponding element in the subsequence.
Check each subsequence generated in step 4 for validity: iterate over the subsequence and check if adjacent elements have at least one common digit using the has_common_digit function. If any adjacent elements do not have a common digit, mark the subsequence as invalid and move on to the next one.
If a valid subsequence is found, compare its length to max_len and update max_len if the length of the new subsequence is longer.
Return max_len as the length of the longest subsequence.
(Optional) Generate the longest subsequence itself by constructing a new list from the elements of arr that correspond to the 1-bits in the binary representation of the longest subsequence.
C++
#include <iostream>#include <vector>#include <string>Â
using namespace std;Â
bool has_common_digit(int a, int b) {Â Â Â Â string a_str = to_string(a);Â Â Â Â string b_str = to_string(b);Â Â Â Â for (char digit : a_str) {Â Â Â Â Â Â Â Â if (b_str.find(digit) != string::npos) {Â Â Â Â Â Â Â Â Â Â Â Â return true;Â Â Â Â Â Â Â Â }Â Â Â Â }Â Â Â Â return false;}Â
vector<int> longest_subsequence(vector<int>& arr) {Â Â Â Â int n = arr.size();Â Â Â Â int max_len = 0;Â Â Â Â vector<int> max_subsequence;Â Â Â Â for (int i = 0; i < (1 << n); i++) {Â Â Â Â Â Â Â Â vector<int> subsequence;Â Â Â Â Â Â Â Â for (int j = 0; j < n; j++) {Â Â Â Â Â Â Â Â Â Â Â Â if (i & (1 << j)) {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â subsequence.push_back(arr[j]);Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â if (subsequence.size() > max_len) {Â Â Â Â Â Â Â Â Â Â Â Â bool valid = true;Â Â Â Â Â Â Â Â Â Â Â Â for (int j = 0; j < subsequence.size() - 1; j++) {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â if (!has_common_digit(subsequence[j], subsequence[j+1])) {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â valid = false;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â break;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â Â Â Â Â if (valid) {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â max_len = subsequence.size();Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â max_subsequence = subsequence;Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â }Â Â Â Â }Â Â Â Â return max_subsequence;}Â
int main() {Â Â Â Â vector<int> arr1 = {1, 12, 44, 29, 33, 96, 89};Â Â Â Â vector<int> arr2 = {12, 23, 45, 43, 36, 97};Â
    cout << "Input: arr1 = ";    for (int x : arr1) {        cout << x << " ";    }    cout << endl;Â
    vector<int> max_subsequence1 = longest_subsequence(arr1);Â
    cout << "Output: " << max_subsequence1.size() << endl;    cout << "The longest sub-sequence is ";    for (int x : max_subsequence1) {        cout << x << " ";    }    cout << endl;Â
    cout << "Input: arr2 = ";    for (int x : arr2) {        cout << x << " ";    }    cout << endl;Â
    vector<int> max_subsequence2 = longest_subsequence(arr2);Â
    cout << "Output: " << max_subsequence2.size() << endl;    cout << "The longest sub-sequence is ";    for (int x : max_subsequence2) {        cout << x << " ";    }    cout << endl;Â
    return 0;} |
Java
import java.util.ArrayList;import java.util.List;Â
class GFG {Â Â Â Â public static boolean hasCommonDigit(int a, int b) {Â Â Â Â Â Â Â Â String aStr = Integer.toString(a);Â Â Â Â Â Â Â Â String bStr = Integer.toString(b);Â Â Â Â Â Â Â Â for (char digit : aStr.toCharArray()) {Â Â Â Â Â Â Â Â Â Â Â Â if (bStr.indexOf(digit) != -1) {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â return true;Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â return false;Â Â Â Â }Â
    public static List<Integer> longestSubsequence(List<Integer> arr) {        int n = arr.size();        int maxLen = 0;        List<Integer> maxSubsequence = new ArrayList<>();        for (int i = 0; i < (1 << n); i++) {            List<Integer> subsequence = new ArrayList<>();            for (int j = 0; j < n; j++) {                if ((i & (1 << j)) != 0) {                    subsequence.add(arr.get(j));                }            }            if (subsequence.size() > maxLen) {                boolean valid = true;                for (int j = 0; j < subsequence.size() - 1; j++) {                    if (!hasCommonDigit(subsequence.get(j), subsequence.get(j + 1))) {                        valid = false;                        break;                    }                }                if (valid) {                    maxLen = subsequence.size();                    maxSubsequence = subsequence;                }            }        }        return maxSubsequence;    }Â
    public static void main(String[] args) {        List<Integer> arr1 = List.of(1, 12, 44, 29, 33, 96, 89);        List<Integer> arr2 = List.of(12, 23, 45, 43, 36, 97);Â
        System.out.print("Input: arr1 = ");        for (int x : arr1) {            System.out.print(x + " ");        }        System.out.println();Â
        List<Integer> maxSubsequence1 = longestSubsequence(arr1);Â
        System.out.println("Output: " + maxSubsequence1.size());        System.out.print("The longest sub-sequence is ");        for (int x : maxSubsequence1) {            System.out.print(x + " ");        }        System.out.println();Â
        System.out.print("Input: arr2 = ");        for (int x : arr2) {            System.out.print(x + " ");        }        System.out.println();Â
        List<Integer> maxSubsequence2 = longestSubsequence(arr2);Â
        System.out.println("Output: " + maxSubsequence2.size());        System.out.print("The longest sub-sequence is ");        for (int x : maxSubsequence2) {            System.out.print(x + " ");        }        System.out.println();    }} |
Python3
def has_common_digit(a, b):    for digit in str(a):        if digit in str(b):            return True    return FalseÂ
def longest_subsequence(arr):    n = len(arr)    max_len = 0    max_subsequence = []    for i in range(2**n):        subsequence = [arr[j] for j in range(n) if (i & (1 << j))]        if len(subsequence) > max_len:            valid = True            for j in range(len(subsequence) - 1):                if not has_common_digit(subsequence[j], subsequence[j+1]):                    valid = False                    break            if valid:                max_len = len(subsequence)                max_subsequence = subsequence    return max_subsequenceÂ
arr1 = [1, 12, 44, 29, 33, 96, 89]arr2 = [12, 23, 45, 43, 36, 97]Â
print("Input: arr1 =", arr1)max_subsequence1 = longest_subsequence(arr1)print("Output:", len(max_subsequence1))print("The longest sub-sequence is", max_subsequence1)Â
print("Input: arr2 =", arr2)max_subsequence2 = longest_subsequence(arr2)print("Output:", len(max_subsequence2))print("The longest sub-sequence is", max_subsequence2) |
C#
using System;using System.Collections.Generic;using System.Linq;Â
class GFG {Â Â Â Â static bool HasCommonDigit(int a, int b)Â Â Â Â {Â Â Â Â Â Â Â Â string aStr = a.ToString();Â Â Â Â Â Â Â Â string bStr = b.ToString();Â Â Â Â Â Â Â Â foreach(char digit in aStr)Â Â Â Â Â Â Â Â {Â Â Â Â Â Â Â Â Â Â Â Â if (bStr.Contains(digit)) {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â return true;Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â return false;Â Â Â Â }Â
    static List<int> LongestSubsequence(List<int> arr)    {        int n = arr.Count;        int maxLen = 0;        List<int> maxSubsequence = new List<int>();        for (int i = 0; i < (1 << n); i++) {            List<int> subsequence = new List<int>();            for (int j = 0; j < n; j++) {                if ((i & (1 << j)) != 0) {                    subsequence.Add(arr[j]);                }            }            if (subsequence.Count > maxLen) {                bool valid = true;                for (int j = 0; j < subsequence.Count - 1;                     j++) {                    if (!HasCommonDigit(                            subsequence[j],                            subsequence[j + 1])) {                        valid = false;                        break;                    }                }                if (valid) {                    maxLen = subsequence.Count;                    maxSubsequence = subsequence;                }            }        }        return maxSubsequence;    }Â
    static void Main()    {        List<int> arr1            = new List<int>{ 1, 12, 44, 29, 33, 96, 89 };        List<int> arr2            = new List<int>{ 12, 23, 45, 43, 36, 97 };Â
        Console.Write("Input: arr1 = ");        Console.WriteLine(string.Join(" ", arr1));Â
        List<int> maxSubsequence1            = LongestSubsequence(arr1);Â
        Console.WriteLine("Output: "                          + maxSubsequence1.Count);        Console.Write("The longest sub-sequence is ");        Console.WriteLine(            string.Join(" ", maxSubsequence1));Â
        Console.Write("Input: arr2 = ");        Console.WriteLine(string.Join(" ", arr2));Â
        List<int> maxSubsequence2            = LongestSubsequence(arr2);Â
        Console.WriteLine("Output: "                          + maxSubsequence2.Count);        Console.Write("The longest sub-sequence is ");        Console.WriteLine(            string.Join(" ", maxSubsequence2));    }} |
Javascript
// Function to check if two numbers have a common digitfunction hasCommonDigit(a, b) {Â Â Â Â const aStr = a.toString();Â Â Â Â const bStr = b.toString();Â Â Â Â for (const digit of aStr) {Â Â Â Â Â Â Â Â if (bStr.includes(digit)) {Â Â Â Â Â Â Â Â Â Â Â Â return true;Â Â Â Â Â Â Â Â }Â Â Â Â }Â Â Â Â return false;}Â
// Function to find the longest subsequence with common digitsfunction longestSubsequence(arr) {Â Â Â Â const n = arr.length;Â Â Â Â let maxLen = 0;Â Â Â Â let maxSubsequence = [];Â Â Â Â for (let i = 0; i < (1 << n); i++) {Â Â Â Â Â Â Â Â const subsequence = [];Â Â Â Â Â Â Â Â for (let j = 0; j < n; j++) {Â Â Â Â Â Â Â Â Â Â Â Â if (i & (1 << j)) {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â subsequence.push(arr[j]);Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â if (subsequence.length > maxLen) {Â Â Â Â Â Â Â Â Â Â Â Â let valid = true;Â Â Â Â Â Â Â Â Â Â Â Â for (let j = 0; j < subsequence.length - 1; j++) {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â if (!hasCommonDigit(subsequence[j], subsequence[j + 1])) {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â valid = false;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â break;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â Â Â Â Â if (valid) {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â maxLen = subsequence.length;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â maxSubsequence = subsequence;Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â }Â Â Â Â }Â Â Â Â return maxSubsequence;}Â
// driver codeÂ
    const arr1 = [1, 12, 44, 29, 33, 96, 89];    const arr2 = [12, 23, 45, 43, 36, 97];Â
    console.log("Input: arr1 =", arr1.join(" "));Â
    const maxSubsequence1 = longestSubsequence(arr1);Â
    console.log("Output:", maxSubsequence1.length);    console.log("The longest sub-sequence is", maxSubsequence1.join(" "));Â
    console.log("Input: arr2 =", arr2.join(" "));Â
    const maxSubsequence2 = longestSubsequence(arr2);Â
    console.log("Output:", maxSubsequence2.length);    console.log("The longest sub-sequence is", maxSubsequence2.join(" ")); |
Input: arr1 = [1, 12, 44, 29, 33, 96, 89] Output: 5 The longest sub-sequence is [1, 12, 29, 96, 89] Input: arr2 = [12, 23, 45, 43, 36, 97] Output: 4 The longest sub-sequence is [12, 23, 43, 36]
Time Complexity: O(2^n) where n is the length of the sequence
Space Complexity: O(n)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



