Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Longest subsequence where each character occurs at least k times
Next article icon

Longest subsequence with at least one character appearing in every string

Last Updated : 21 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 2 
{“ab”, “bc”} is the required sub-sequence 
with ‘b’ as the common character.
Input: str = {“a”, “b”, “c”} 
Output: 1 

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:
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
#define MAX 26
 
// Function to return the length of the longest
// sub-sequence with at least one
// common character in every string
int largestSubSeq(string arr[], int n)
{
 
    // count[0] will store the number of strings
    // which contain 'a', count[1] will store the
    // number of strings which contain 'b' and so on..
    int count[MAX] = { 0 };
 
    // For every string
    for (int i = 0; i < n; i++) {
        string str = arr[i];
 
        // Hash array to set which character is
        // present in the current string
        bool hash[MAX] = { 0 };
        for (int j = 0; j < str.length(); j++) {
            hash[str[j] - 'a'] = true;
        }
 
        for (int j = 0; j < MAX; j++) {
 
            // If current character appears in the
            // string then update its count
            if (hash[j])
                count[j]++;
        }
    }
 
    return *(max_element(count, count + MAX));
}
 
// Driver code
int main()
{
    string arr[] = { "ab", "bc", "de" };
    int n = sizeof(arr) / sizeof(string);
 
    cout << largestSubSeq(arr, n);
 
    return 0;
}
 
 

Java




// Java implementation of the approach
 
class GFG
{
         
    static int MAX = 26;
     
    // Function to return the length of the longest
    // sub-sequence with at least one
    // common character in every string
    static int largestSubSeq(String arr[], int n)
    {
     
        // count[0] will store the number of strings
        // which contain 'a', count[1] will store the
        // number of strings which contain 'b' and so on..
        int [] count = new int[MAX];
     
        // For every string
        for (int i = 0; i < n; i++) {
            String str = arr[i];
     
            // Hash array to set which character is
            // present in the current string
            boolean [] hash = new boolean[MAX];
             
             
            for (int j = 0; j < str.length(); j++) {
                hash[str.charAt(j) - 'a'] = true;
            }
     
            for (int j = 0; j < MAX; j++) {
     
                // If current character appears in the
                // string then update its count
                if (hash[j])
                    count[j]++;
            }
        }
         
        int max = -1;
     
        for(int i=0;i< MAX; i++)
        {
            if(max < count[i])
                max = count[i];
        }
        return max;
    }
     
    // Driver code
    public static void main (String[] args)
    {
         
        String arr[] = { "ab", "bc", "de" };
        int n = arr.length;
     
        System.out.println(largestSubSeq(arr, n));
     
 
    }
 
 
}
 
// This code is contributed by ihritik
 
 

Python3




# Python3 implementation of the approach
MAX = 26
 
# Function to return the length of the longest
# sub-sequence with at least one
# common character in every string
def largestSubSeq(arr, n):
     
    # count[0] will store the number of strings
    # which contain 'a', count[1] will store the
    # number of strings which contain 'b' and so on..
    count = [0] * MAX
     
    # For every string
    for i in range(n):
        string = arr[i]
         
        # Hash array to set which character is
        # present in the current string
        _hash = [False] * MAX
        for j in range(len(string)):
            _hash[ord(string[j]) - ord('a')] = True
         
        for j in range(MAX):
             
            # If current character appears in the
            # string then update its count
            if _hash[j] == True:
                count[j] += 1
                 
    return max(count)
 
# Driver code
if __name__ == "__main__":
    arr = [ "ab", "bc", "de" ]
    n = len(arr)
    print(largestSubSeq(arr, n))
 
# This code is contributed by
# sanjeev2552
 
 

C#




// C# implementation of the approach
using System;
 
class GFG
{
         
    static int MAX = 26;
     
    // Function to return the length of the longest
    // sub-sequence with at least one
    // common character in every string
    static int largestSubSeq(string [] arr, int n)
    {
     
        // count[0] will store the number of strings
        // which contain 'a', count[1] will store the
        // number of strings which contain 'b' and so on..
        int [] count = new int[MAX];
     
        // For every string
        for (int i = 0; i < n; i++)
        {
            string str = arr[i];
     
            // Hash array to set which character is
            // present in the current string
            bool [] hash = new bool[MAX];
             
             
            for (int j = 0; j < str.Length; j++)
            {
                hash[str[j] - 'a'] = true;
            }
     
            for (int j = 0; j < MAX; j++)
            {
     
                // If current character appears in the
                // string then update its count
                if (hash[j])
                    count[j]++;
            }
        }
         
        int max = -1;
     
        for(int i=0;i< MAX; i++)
        {
            if(max < count[i])
                max = count[i];
        }
        return max;
    }
     
    // Driver code
    public static void Main ()
    {
         
        string [] arr = { "ab", "bc", "de" };
        int n = arr.Length;
     
        Console.WriteLine(largestSubSeq(arr, n));
    }
}
 
// This code is contributed by ihritik
 
 

Javascript




<script>
 
// Javascript implementation of the approach
 
var MAX = 26;
 
// Function to return the length of the longest
// sub-sequence with at least one
// common character in every string
function largestSubSeq(arr, n)
{
 
    // count[0] will store the number of strings
    // which contain 'a', count[1] will store the
    // number of strings which contain 'b' and so on..
    var count = Array(MAX).fill(0);
 
    // For every string
    for (var i = 0; i < n; i++) {
        var str = arr[i];
 
        // Hash array to set which character is
        // present in the current string
        var hash = Array(MAX).fill(0);
        for (var j = 0; j < str.length; j++) {
            hash[str[j].charCodeAt(0) - 'a'.charCodeAt(0)] = true;
        }
 
        for (var j = 0; j < MAX; j++) {
 
            // If current character appears in the
            // string then update its count
            if (hash[j])
                count[j]++;
        }
    }
 
    return count.reduce((a,b)=>Math.max(a,b));
}
 
// Driver code
var arr = ["ab", "bc", "de" ];
var n = arr.length;
document.write( largestSubSeq(arr, n));
 
</script>
 
 
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.



Next Article
Longest subsequence where each character occurs at least k times

G

gp6
Improve
Article Tags :
  • DSA
  • Hash
  • Strings
  • subsequence
Practice Tags :
  • Hash
  • Strings

Similar Reads

  • Longest subsequence where every character appears at-least k times
    Given a string and a number k, find the longest subsequence of a string where every character appears at-least k times. Examples: Input: str = "geeksforgeeks", k = 2Output: geeksgeeksExplanation: Every character in the output subsequence appears at-least 2 times. Input : str = "aabbaabacabb", k = 5O
    12 min read
  • Longest Subsequence with at least one common digit in every element
    Given an array. The task is to find the length of the longest subsequence in which all elements must have at least one digit in common. Examples: Input : arr[] = { 11, 12, 23, 74, 13 } Output : 3 Explanation: The elements 11, 12, and 13 have the digit '1' as common. So it is the required longest sub
    9 min read
  • Longest subsequence with different adjacent characters
    Given string str. The task is to find the longest subsequence of str such that all the characters adjacent to each other in the subsequence are different. Examples:   Input: str = "ababa" Output: 5 Explanation: "ababa" is the subsequence satisfying the condition Input: str = "xxxxy" Output: 2 Explan
    11 min read
  • Longest subsequence where each character occurs at least k times
    Given a string 's' and an integer k, find other string 't' such that 't' is the largest subsequence of given string 's' and each character of 't' must occur at least k times in string s. Examples : Input s = "geeksforgeeks" k = 2Output geeksgeeksExplanation 'g', 'e', 'k', and 's' appear twice or mor
    3 min read
  • Longest Common Subsequence with no repeating character
    Given two strings s1 and s2, the task is to find the length of the longest common subsequence with no repeating character. Examples: Input: s1= "aabbcc", s2= "aabc"Output: 3Explanation: "aabc" is longest common subsequence but it has two repeating character 'a'.So the required longest common subsequ
    10 min read
  • Longest substring where all the characters appear at least K times | Set 3
    Given a string str and an integer K, the task is to find the length of the longest substring S such that every character in S appears at least K times. Examples: Input: str = “aabbba”, K = 3Output: 6Explanation: In substring "aabbba", each character repeats at least k times and its length is 6. Inpu
    12 min read
  • Longest Non-Increasing Subsequence in a Binary String
    Given a binary string S of size N, the task is to find the length of the longest non-increasing subsequence in the given string S. Examples: Input: S = "0101110110100001011"Output: 12 Explanation: The longest non-increasing subsequence is "111111100000", having length equal to 12. Input: S = 10101Ou
    8 min read
  • Length of longest increasing subsequence in a string
    Given a string S, the task is to find the length of the longest increasing subsequence present in the given string. A sequence of characters placed in increasing order of their ASCII values is called an increasing sequence. Examples: Input: S = "abcfgffs"Output: 6Explanation: Subsequence "abcfgs" is
    7 min read
  • Largest sub-string where all the characters appear at least K times
    Given a string str and an integer K, the task is to find the length of the longest sub-string S' such that every character in S' appears at least K times. Input: s = "xyxyyz", k = 2 Output: 5 "xyxyy" is the longest sub-string where every character appears at least twice.Input: s = "geeksforgeeks", k
    7 min read
  • Longest Subsequence with difference between characters equals to K
    Given a string S consisting of lowercase letters. Find the longest subsequence of S such that the difference between the maximum and minimum occurring characters in the subsequence is exactly K. Examples: Input: S = 'abcdeg' and K = 4Output: abcde Input: S = 'daaaabbbadddddeeee', K = 1Output: dddddd
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences