Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Longest Subsequence with at least one common digit in every element
Next article icon

Longest Subsequence with at least one common digit in every element

Last Updated : 06 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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-sequence.

Input : arr[] = { 12, 90, 67, 78, 45 } 
Output : 2 

Normal Approach: Find all the subsequences of the array and find the subsequence in which every element must have a common digit. Then we have to find the longest such subsequence and print the length of that subsequence. This method will take exponential time complexity.

Efficient Approach: The idea is to take a hash array of size 10 to store the count of digits from 0-9 appearing in the elements of the array. Traverse the array and for every element of the array, find the unique digits in that element and increment their count in the hash array. Now, the digit with the maximum count in the hash array indicates that it is the maximum occurring common digit among the elements of the array. So, the length of the required longest subsequence will be the count of maximum in the hash array.

Let us take an example, 

Let the array be arr[] = {11, 12, 13, 24} 
Initially the count array is { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
1st element is 11 so digits are 1 and 1 (but 1 will be counted once} 
count array is { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 }
2nd element is 12 so digits are 1, 2 
count array is { 0, 2, 1, 0, 0, 0, 0, 0, 0, 0 }
3rd element is 13 so digits are 1, 3 
count array is { 0, 3, 1, 1, 0, 0, 0, 0, 0, 0 }
4th element is 24 so digits are 2, 4 
count array is { 0, 3, 2, 1, 1, 0, 0, 0, 0, 0 }
So the maximum value in count array is 3 
Therefore, 3 will be the answer 

Below is the implementation of the above approach: 

C++
// C++ program to find the length of subsequence which has // atleast one digit common among all its elements #include <bits/stdc++.h> using namespace std;  // If the number contains a digit increase // the count by 1 (even if it has multiple // same digit the count should be increased // by only once) void count_(int count[], int e) {     // Hash to make it sure that a digit     // is counted only once     bool hash[10];      // Set the hash to its initial value     memset(hash, false, sizeof(hash));      // Extract the digits     while (e > 0) {          // If the digit did not appear before         if (hash[e % 10] == false)              // Increase the count             count[e % 10]++;          // Mark the digit as visited         hash[e % 10] = true;          // Delete the digit         e /= 10;     } }  // Function to find the length of subsequence which has // atleast one digit common among all its elements void find_subsequence(int arr[], int n) {     // Count of digits     int count[10];      // Set the initial value to zero     memset(count, 0, sizeof(count));     for (int i = 0; i < n; i++) {          // Extract the digits of the element         // and increase the count         count_(count, arr[i]);     }      // Longest subsequence     int longest = 0;      // Get the longest subsequence     for (int i = 0; i < 10; i++)         longest = max(count[i], longest);      // Print the length of longest subsequence     cout << longest << endl; }  // Driver code int main() {     int arr[] = { 11, 12, 23, 74, 13 };      int n = sizeof(arr) / sizeof(arr[0]);      find_subsequence(arr, n);      return 0; } 
Java
// Java program to find the length of subsequence which has // atleast one digit common among all its elements  import java.io.*;  class GFG {  // If the number contains a digit increase // the count by 1 (even if it has multiple // same digit the count should be increased // by only once) static void count_(int count[], int e) {     // Hash to make it sure that a digit     // is counted only once     boolean hash[] = new boolean[10];      // Set the hash to its initial value     //memset(hash, false, sizeof(hash));      // Extract the digits     while (e > 0) {          // If the digit did not appear before         if (hash[e % 10] == false)              // Increase the count             count[e % 10]++;          // Mark the digit as visited         hash[e % 10] = true;          // Delete the digit         e /= 10;     } }  // Function to find the length of subsequence which has // atleast one digit common among all its elements static void find_subsequence(int arr[], int n) {     // Count of digits     int count[] = new int[10];      // Set the initial value to zero     //memset(count, 0, sizeof(count));     for (int i = 0; i < n; i++) {          // Extract the digits of the element         // and increase the count         count_(count, arr[i]);     }      // Longest subsequence     int longest = 0;      // Get the longest subsequence     for (int i = 0; i < 10; i++)         longest = Math.max(count[i], longest);      // Print the length of longest subsequence     System.out.print( longest); }          // Driver code     public static void main (String[] args) {             int arr[] = { 11, 12, 23, 74, 13 };      int n =arr.length;      find_subsequence(arr, n);      } } // This code is contributed // by shs 
Python3
# Python3 program to find the length  # of subsequence which has atleast  # one digit common among all its elements   # If the number contains a digit increase  # the count by 1 (even if it has multiple  # same digit the count should be increased  # by only once)  def count_(count, e):      # Hash to make it sure that a digit      # is counted only once      hash = [False] * 10      # Extract the digits      while (e > 0):           # If the digit did not          # appear before          if (hash[e % 10] == False) :              # Increase the count              count[e % 10] += 1          # Mark the digit as visited          hash[e % 10] = True          # Delete the digit          e //= 10  # Function to find the length of  # subsequence which has atleast  # one digit common among all its elements  def find_subsequence(arr, n) :      # Count of digits      count = [0] * 10      for i in range ( n) :           # Extract the digits of the element          # and increase the count          count_(count, arr[i])      # Longest subsequence      longest = 0      # Get the longest subsequence      for i in range(10) :         longest = max(count[i], longest)      # Print the length of      # longest subsequence      print (longest)  # Driver code  if __name__ == "__main__":      arr = [ 11, 12, 23, 74, 13 ]      n = len(arr)      find_subsequence(arr, n)  # This code is contributed # by ChitraNayal 
C#
// C# program to find the length  // of subsequence which has atleast  // one digit common among all its elements using System;  class GFG  {  // If the number contains a digit increase // the count by 1 (even if it has multiple // same digit the count should be increased // by only once) static void count_(int []count, int e) {     // Hash to make it sure that a      // digit is counted only once     bool []hash = new bool[10];      // Set the hash to its initial value     //memset(hash, false, sizeof(hash));      // Extract the digits     while (e > 0)      {          // If the digit did not          // appear before         if (hash[e % 10] == false)              // Increase the count             count[e % 10]++;          // Mark the digit as visited         hash[e % 10] = true;          // Delete the digit         e /= 10;     } }  // Function to find the length of  // subsequence which has atleast  // one digit common among all its elements static void find_subsequence(int []arr,                               int n) {     // Count of digits     int []count = new int[10];      // Set the initial value to zero     //memset(count, 0, sizeof(count));     for (int i = 0; i < n; i++)      {          // Extract the digits of the element         // and increase the count         count_(count, arr[i]);     }      // Longest subsequence     int longest = 0;      // Get the longest subsequence     for (int i = 0; i < 10; i++)         longest = Math.Max(count[i], longest);      // Print the length of      // longest subsequence     Console.WriteLine(longest); }  // Driver code public static void Main ()  {     int []arr = { 11, 12, 23, 74, 13 };      int n = arr.Length;      find_subsequence(arr, n); } }  // This code is contributed // by Shashank 
JavaScript
<script>  // Javascript program to find the length of subsequence which has // atleast one digit common among all its elements  // If the number contains a digit increase // the count by 1 (even if it has multiple // same digit the count should be increased // by only once) function count_(count, e) {     // Hash to make it sure that a digit     // is counted only once     var hash = Array(10).fill(false);      // Extract the digits     while (e > 0) {          // If the digit did not appear before         if (hash[e % 10] == false)              // Increase the count             count[e % 10]++;          // Mark the digit as visited         hash[e % 10] = true;          // Delete the digit         e /= 10;     } }  // Function to find the length of subsequence which has // atleast one digit common among all its elements function find_subsequence(arr, n) {     // Count of digits     var count = Array(10).fill(0);      for (var i = 0; i < n; i++) {          // Extract the digits of the element         // and increase the count         count_(count, arr[i]);     }      // Longest subsequence     var longest = 0;      // Get the longest subsequence     for (var i = 0; i < 10; i++)         longest = Math.max(count[i], longest);      // Print the length of longest subsequence     document.write( longest); }  // Driver code var arr = [ 11, 12, 23, 74, 13 ]; var n = arr.length; find_subsequence(arr, n);  </script>          

Output
3 

Complexity Analysis:

  • Time Complexity: O(N)
  • Auxiliary Space: O(N)

Next Article
Longest Subsequence with at least one common digit in every element

A

andrew1234
Improve
Article Tags :
  • Competitive Programming
  • DSA
  • Arrays
  • subsequence
  • Hash
  • frequency-counting
  • Constructive Algorithms
Practice Tags :
  • Arrays
  • Hash

Similar Reads

    Longest subsequence such that adjacent elements have at least one common digit
    Given an array arr[], the task is to find the length of the longest sub-sequence such that adjacent elements of the subsequence have at least one digit in common.Examples: Input: arr[] = [1, 12, 44, 29, 33, 96, 89] Output: 5 Explanation: The longest sub-sequence is [1 12 29 96 89]Input: arr[] = [12,
    15+ min read
    Longest subarray such that adjacent elements have at least one common digit | Set - 2
    Given an array of N integers, the task is to find the length of the longest subarray such that adjacent elements of the subarray have at least one digit in common.Examples: Input : arr[] = {12, 23, 45, 43, 36, 97} Output : 3 Explanation: The subarray is 45 43 36 which has 4 common in 45, 43 and 3 co
    12 min read
    Length of the longest subsequence consisting of distinct elements
    Given an array arr[] of size N, the task is to find the length of the longest subsequence consisting of distinct elements only. Examples: Input: arr[] = {1, 1, 2, 2, 2, 3, 3} Output: 3 Explanation: The longest subsequence with distinct elements is {1, 2, 3} Input: arr[] = { 1, 2, 3, 3, 4, 5, 5, 5 }
    4 min read
    Find the Longest Common Subsequence (LCS) in given K permutations
    Given K permutations of numbers from 1 to N in a 2D array arr[][]. The task is to find the longest common subsequence of these K permutations. Examples: Input: N = 4, K = 3arr[][] = {{1, 4, 2, 3}, {4, 1, 2, 3}, {1, 2, 4, 3}}Output: 3Explanation: Longest common subsequence is {1, 2, 3} which has leng
    10 min read
    Length of longest subsequence consisting of distinct adjacent elements
    Given an array arr[], the task is to find the length of the longest subsequence of the array arr[] such that all adjacent elements in the subsequence are different. Examples: Input: arr[] = {4, 2, 3, 4, 3}Output: 5Explanation:The longest subsequence where no two adjacent elements are equal is {4, 2,
    5 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