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

Last Updated : 14 Sep, 2023

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:
The longest sub-sequence is {1 12 29 96 89}
Input: arr[] = {12, 23, 45, 43, 36, 97}
Output:
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 ` `using` `namespace` `std;`   `// Returns length of maximum length subsequence` `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[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 code` `int` `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 subsequence` `static` `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 code` `public` `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 subsequence` `def` `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 code` `arr ``=` `[``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 digit` `using` `System;`   `class` `GFG` `{`   `// Returns length of maximum length subsequence` `static` `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 code` `public` `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

 ``

Output

```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 ` `using` `namespace` `std;`   `// Returns length of maximum length subsequence` `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[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 code` `int` `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

 ``

## PHP

 ` 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` `?>`

Output

```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 ` `#include ` `#include `   `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 longestSubsequence(List arr) {` `        ``int` `n = arr.size();` `        ``int` `maxLen = ``0``;` `        ``List maxSubsequence = ``new` `ArrayList<>();` `        ``for` `(``int` `i = ``0``; i < (``1` `<< n); i++) {` `            ``List 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 arr1 = List.of(``1``, ``12``, ``44``, ``29``, ``33``, ``96``, ``89``);` `        ``List 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 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 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 digit` `function` `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 digits` `function` `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(``" "``));`

Output

```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)

Previous
Next