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 String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Queries to check if string B exists as substring in string A
Next article icon

Check if two same sub-sequences exist in a string or not

Last Updated : 30 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string, the task is to check if there exist two equal sub-sequences in the given string. Two sub-sequences are said to be equal if they have the same characters arranged in the same lexicographical order but the position of characters differs from that in the original string. 
Examples: 
 

Input: str = “geeksforgeeks” 
Output: YES 
Two possible sub-sequences are “geeks” and “geeks”. 
Input: str = “bhuvan” 
Output: NO

 

Approach: The approach to solving this problem is to check if any character appears more than once. Since the minimal length of matching subsequence can be 1, hence if a character occurrence in a string more than once then two similar subsequences is possible. Initialize a freq[] array of length 26. Iterate over the string and increment the frequency of the characters. Iterate over the freq array and check if freq[i] for any i in the range of 0-26 is more than 1, then it is possible. 
Below is the implementation of the above approach. 
 

C++




// C++ program to Check if
// similar subsequences exist or not
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if similar subsequences
// occur in a string or not
bool check(string s, int l)
{
 
    int freq[26] = { 0 };
    // iterate and count the frequency
    for (int i = 0; i < l; i++) {
        freq[s[i] - 'a']++; // counting frequency of the letters
    }
 
    // check if frequency is more
    // than once of any character
    for (int i = 0; i < 26; i++) {
        if (freq[i] >= 2)
            return true;
    }
    return false;
}
// Driver Code
int main()
{
    string s = "geeksforgeeks";
    int l = s.length();
    if (check(s, l))
        cout << "YES";
    else
        cout << "NO";
 
    return 0;
}
 
 

Java




// Java program to Check
// if similar subsequences
// exist or not
import java.io.*;
import java.util.*;
import java.util.Arrays;
 
class GFG
{
// Function to check if
// similar subsequences
// occur in a string or not
static boolean check(String s,
                     int l)
{
    int freq[] = new int[26];
    Arrays.fill(freq, 0);
     
    // iterate and count
    // the frequency
    for (int i = 0; i < l; i++)
    {
        // counting frequency
        // of the letters
        freq[s.charAt(i) - 'a']++;
    }
 
    // check if frequency is more
    // than once of any character
    for (int i = 0; i < 26; i++)
    {
        if (freq[i] >= 2)
            return true;
    }
    return false;
}
 
// Driver Code
public static void main(String args[])
{
    String s = "geeksforgeeks";
    int l = s.length();
    if (check(s, l))
        System.out.print("YES");
    else
        System.out.print("NO");
}
}
 
 

Python3




# Python 3 program to Check if
# similar subsequences exist or not
 
# Function to check if similar subsequences
# occur in a string or not
def check(s, l):
    freq = [0 for i in range(26)]
     
    # iterate and count the frequency
    for i in range(l):
         
        # counting frequency of the letters
        freq[ord(s[i]) - ord('a')] += 1
         
    # check if frequency is more
    # than once of any character
    for i in range(26):
        if (freq[i] >= 2):
            return True
 
    return False
 
# Driver Code
if __name__ == '__main__':
    s = "geeksforgeeks"
    l = len(s)
    if (check(s, l)):
        print("YES")
    else:
        print("NO")
 
# This code is contributed by
# Sahil_Shelangia
 
 

C#




// C# program to Check if similar subsequences
// exist or not
using System;
using System.Collections.Generic;            
 
class GFG
{
     
// Function to check if similar subsequences
// occur in a string or not
static bool check(String s, int l)
{
    int []freq = new int[26];
     
    // iterate and count the frequency
    for (int i = 0; i < l; i++)
    {
        // counting frequency of the letters
        freq[s[i] - 'a']++;
    }
 
    // check if frequency is more
    // than once of any character
    for (int i = 0; i < 26; i++)
    {
        if (freq[i] >= 2)
            return true;
    }
    return false;
}
 
// Driver Code
public static void Main(String []args)
{
    String s = "geeksforgeeks";
    int l = s.Length;
    if (check(s, l))
        Console.WriteLine("YES");
    else
        Console.WriteLine("NO");
}
}
 
// This code is contributed by PrinciRaj1992
 
 

Javascript




<script>
 
// JavaScript program to Check
// if similar subsequences
// exist or not
 
// Function to check if
// similar subsequences
// occur in a string or not
function check(s, l)
{
    let freq = new Array(26).fill(0);
       
    // iterate and count
    // the frequency
    for (let i = 0; i < l; i++)
    {
        // counting frequency
        // of the letters
        freq[s[i].charCodeAt() - 'a'.charCodeAt()]++;
    }
   
    // check if frequency is more
    // than once of any character
    for (let i = 0; i < 26; i++)
    {
        if (freq[i] >= 2)
            return true;
    }
    return false;
}
  
// Driver Code
 
    let s = "geeksforgeeks";
    let l = s.length;
    if (check(s, l))
        document.write("YES");
    else
        document.write("NO");
        
</script>
 
 
Output: 
YES

 

Time Complexity: O(N) 
Auxiliary Space: O(1) 
Note: If the length of a similar subsequence was mentioned, then the approach to solve the problem will also be different. The approach to check if a string contains two repeated subsequences of length two or more is discussed in this post. 
 



Next Article
Queries to check if string B exists as substring in string A

I

IshitaBhuiya
Improve
Article Tags :
  • DSA
  • Strings
Practice Tags :
  • Strings

Similar Reads

  • Check if there exists any sub-sequence in a string which is not palindrome
    Given a string s consisting of lowercase characters, the task is to check if there exists any subsequence in the string which is not a palindrome. If there is at least 1 such subsequence, then return true, otherwise return false. Examples: Input : str = "abaab"Output: YesExplanation: Subsequences "a
    7 min read
  • Check if two strings are same or not
    Given two strings, the task is to check if these two strings are identical(same) or not. Consider case sensitivity. Examples: Input: s1 = "abc", s2 = "abc" Output: Yes Input: s1 = "", s2 = "" Output: Yes Input: s1 = "GeeksforGeeks", s2 = "Geeks" Output: No Approach - By Using (==) in C++/Python/C#,
    7 min read
  • Queries to check if string B exists as substring in string A
    Given two strings A, B and some queries consisting of an integer i, the task is to check whether the sub-string of A starting from index i and ending at index i + length(B) - 1 equals B or not. If equal then print Yes else print No. Note that i + length(B) will always be smaller than length(A). Exam
    15+ min read
  • Queries to check if substring[L...R] is palindrome or not
    Given a string str and Q queries. Every query consists of two numbers L and R. The task is to print if the sub-string[L...R] is palindrome or not. Examples: Input: str = "abacccde", Q[][] = {{0, 2}, {1, 2}, {2, 4}, {3, 5}} Output: Yes No No Yes Input: str = "abaaab", Q[][] = {{0, 1}, {1, 5}} Output:
    13 min read
  • Check if two strings are same or not without using library functions
    Given two strings S1 and S2, the task is to check whether they are the same or not without using string library functions. Examples: Input: S1 = ”GeeksForGeeks”, S2 = ”GeeksForGeeks”Output: TrueExplanation:S1 and S2 are the same strings Input: S1 = ”GeeksForGeeks”, S2 = ”GeeksforGeeks”Output: False
    5 min read
  • Check if Prefix String exists in the Array
    Given an array of strings, the task is to print "Yes" if it contains a string that is a prefix of another string otherwise, print "No". Examples: Input: arr[] = {"rud", "rudra", "rahi"}Output: YesExplanation: arr[0] = "rud" is a prefix of arr[1] = "rudra", that's why "Yes" is the output. Input: arr[
    10 min read
  • Check if two strings are permutation of each other
    Write a function to check whether two given strings are Permutation of each other or not. A Permutation of a string is another string that contains same characters, only the order of characters can be different. For example, "abcd" and "dabc" are Permutation of each other. We strongly recommend that
    14 min read
  • Check if given words are present in a string
    Given a big string and an array of small strings, all of which are smaller in length than the big string. The task is to create an array of booleans, where each boolean represents whether the small string at that index in the array of small strings is contained in the big string. Note : that you can
    15+ min read
  • Consecutive sequenced numbers in a string
    Given a string s that contains only numeric digits, we need to check whether that strings contains numbers in a consecutive sequential manner in increasing order. If the string contains a valid sequence of consecutive integers, print "Yes" followed by the starting number of the sequence. Otherwise,
    6 min read
  • Check if a string follows a^nb^n pattern or not
    Given string str, return true string follows pattern anbn, i.e., it has a's followed by b's such that the number of a's and b's are same. Examples: Input : str = "aabb" Output : Yes Input : str = "abab" Output : No Input : str = "aabbb" Output : No The idea is to first count a's. If number of a's is
    8 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