- Hash, HashSet, Strings

Check if a pair of strings exists that starts with and without the character K or not

Given an array arr[] consisting of N strings of lowercase characters and a character K such that any string may start with the character K, the task is to check if there exists any pair of strings that are starting and not starting (‘!’) with the character K. If found to be true, then print “Yes“. Otherwise, print “No“.Examples:Input: arr[] = {“a”, “!a”, “b”, “!c”, “d”, “!d”}, K = ‘!’Output: YesExplanation:There exists valid pairs of the strings are {(“a”, “!a”), (“!d”, “d”)}.Input: arr[] = {“red”, “red”, “red”, “!orange”, “yellow”, “!blue”, “cyan”, “!green”, “brown”, “!gray”}, K = ‘!’Output: NoNaive Approach: The simplest approach to solve the given problem is to find all possible pairs from the array and check if the strings pair satisfy the given condition or not.Time Complexity: O(N2*M), where M is the maximum length of the string in the given array arr[].Auxiliary Space: O(1)Efficient Approach: The above approach can also be solved by using dictionary. Follow the steps below to solve the problem:Initialize a dictionary, say, visited to store the previously visited strings.Iterate over the list arr[] and in each iteration, if the starting character of the current string is the character K then check for string without the character K in visited otherwise, check for the string with the character K in visited. If the string is found then return “Yes“.In each iteration, add the string S into the map visited.After completing the above steps, print “No” if the above conditions are not satisfied.Below is the implementation of the above approach:Python3  def checkhappy(arr, K, N):            visited = set()          for s in arr:                          if(s[0] == K):            if s[1:] in visited:                return ‘Yes’                                else:            if (K + s) in visited:                return ‘Yes’                          visited.add(s)      return “No”    if __name__ == ‘__main__’:              arr = [‘a’, ‘! a’, ‘b’, ‘! c’, ‘d’, ‘! d’]    K = ‘!’    N = len(arr)          print(checkhappy(arr, K, N))Output:
No
Time Complexity: O(N)Auxiliary Space: O(1)Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.