Problem LinkAuthor: Bhuvnesh Jain Tester: Hasan Jaddouh Editorialist: Bhuvnesh Jain DifficultyCAKEWALK PrerequisitesLooping Techniques ProblemYou are given a string $S$ and you are required to find whether there exists $2$ different nonempty subsequences in $S$ which are equal. Quick ExplanationCheck whether there exist 2 equal characters in the string. ExplanationLemma : If there exists a solution, then the smallest such equal subsequences will be of length 1. Proof : Let us assume the solution exists and the length of smallest equal subsequence is greater than $1$. Let the subsequences be $a$ and $b$. Since they are equal, they should be of same length and each character should be same on every index. Since, the 2 subsequence should differ by atleast one index, but the subsequence being equals means that we get a smaller subsequence of length $1$ which is also equal contradicting our assumption. Hence, the lemma is correct. Now, to implement the above claim, we can simply loop over all the possible pair of positions and check if they are equal or not. The complexity of the above approach will be $O(N^2)$, which is sufficient to pass the problem. Actually, the above solution can be made more efficient by simply creating a frequency array of size 26 (or equivalently Alphabet size) and storing the count of every character in it. The answer exist if the frequency of any alphabet is more than 1. The complexity of this approach is $O(N + ALPHABET)$. Bonus problemWhat is the smallest length of string required to be sure that answer will be always "yes" irrespective of the string? Time Complexity$O(N^2)$ or $O(N + ALPHABET)$, where $N = $ length of string. Space Complexity$O(N)$ Solution Links
This question is marked "community wiki".
asked 12 Sep '17, 22:44

Can we say that the Time Complexity will never be greater than 26 i.e no of total alphabets. thus Time Complexity O(N + Albhabet)<O(26). As we can can but a condition that :
Thus, bonus Q> min length of string required is 27 for ans to be always "yes" irrespective of any string you give as input. answered 18 Sep '17, 00:48

Mysolution import java.io.; import java.util.; class Codechef1 { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int T=sc.nextInt(); int i; int l; for(i=0;i<t;i++) {="" string="" s="sc.next();" l="s.length()1;" int="" j;="" hashset<character=""> hset=new HashSet<character>(); for(j=0;j<=l;j++) { hset.add(s.charAt(j)); } System.out.println(hset); if(hset.size()==s.length()) { System.out.println("No"); } else if(hset.size()2<s.length()); { System.out.println("yes"); } } } } Happycoding answered 18 Sep '17, 18:49

The two subsequences might have common elements, so in the proof of the lemma it should be the character at index $i$ such that $a_i \neq b_i$, which is guaranteed to exist and is not necessarily the first.