VOOZH about

URL: https://www.geeksforgeeks.org/dsa/longest-subsequence-with-at-least-one-character-appearing-in-every-string/

⇱ Longest subsequence with at least one character appearing in every string - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest subsequence with at least one character appearing in every string

Last Updated : 21 Dec, 2022

Given a string array arr[], the task is to find the longest subsequence of the array with at least one character appearing in all the strings. Note that all the strings contain only lowercase English alphabets.
Examples: 

Input: str = {"ab", "bc", "de"} 
Output:
{"ab", "bc"} is the required sub-sequence 
with 'b' as the common character.
Input: str = {"a", "b", "c"} 
Output:


Approach: Create a count[] array such that count[0] will store the number of strings which contain 'a', count[1] will store the number of strings that contain 'b' and so on... 
Now, it's clear that the answer will be the maximum value from the count[] array. In order to update this array start traversing the string array and for every string, mark which characters are present in the current string in a hash[] array. 
And after the traversal, for every character which is present in the current string updates its count in the count[] array.
Below is the implementation of the above approach:
 


Output: 
2

 

Time Complexity: O(n * l), where n is the size of the given str array and l is the maximum length of a string in the array.
Auxiliary Space: O(26) ? O(1), no extra space is required, so it is a constant.

Comment
Article Tags: