Most frequent word in first String which is not present in second String | Python3 implementation of above approach ; Function to return frequent word from S1 that isn 't present in S2 ; create map of banned words ; find smallest and most frequent word ; check if word is not banned ; return answer ; Driver Code
from collections import defaultdict NEW_LINE def smallestFreq ( S1 , S2 ) : NEW_LINE INDENT banned = defaultdict ( lambda : 0 ) NEW_LINE i = 0 NEW_LINE while i < len ( S2 ) : NEW_LINE INDENT s = " " NEW_LINE while i < len ( S2 ) and S2 [ i ] != ' ▁ ' : NEW_LINE INDENT s += S2 [ i ] NEW_LINE i += 1 NEW_LINE DEDENT i += 1 NEW_LINE banned [ s ] += 1 NEW_LINE DEDENT result = defaultdict ( lambda : 0 ) NEW_LINE ans = " " NEW_LINE freq = 0 NEW_LINE i = 0 NEW_LINE while i < len ( S1 ) : NEW_LINE INDENT s = " " NEW_LINE while i < len ( S1 ) and S1 [ i ] != ' ▁ ' : NEW_LINE INDENT s += S1 [ i ] NEW_LINE i += 1 NEW_LINE DEDENT i += 1 NEW_LINE if banned [ s ] == 0 : NEW_LINE INDENT result [ s ] += 1 NEW_LINE if ( result [ s ] > freq or ( result [ s ] == freq and s < ans ) ) : NEW_LINE INDENT ans = s NEW_LINE freq = result [ s ] NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S1 = " geeks ▁ for ▁ geeks ▁ is ▁ best ▁ place ▁ to ▁ learn " NEW_LINE S2 = " bad ▁ place " NEW_LINE print ( smallestFreq ( S1 , S2 ) ) NEW_LINE DEDENT