Hash Tables: Ransom Note

  • + 5 comments

    I just gave a function that takes two arrays named magazine and note

    Code is:

    def checkMagazine(magazine, note):
            l1 = len(note)
            l2 = len(magazine)
            magazine.sort()
            note.sort()
            i = 0
            j = 0
            count = 0
            while i<l1 and j<l2:
                    if note[i] == magazine[j]:
                            count += 1
                            i += 1
                    j += 1
            if count == l1:
                    print ('Yes')
            else:
                    print('No')
    

    We have to find all words of note in magazine (for answer to be 'yes'). The words in note may not follow the same order in magazine (check eg 2). Also try to check the difference between eg1 and eg2.

    eg 1:

        magazine: I understood what you said. 
    
        note: I you said
    

    eg 2:

        magazine: check the words carefully in this sentence hope you check properly
    
        note: words this properly check check
    

    our code should work for both eg1 and eg2, So, I sorted both magazine and note, by magazine.sort() and note.sort() it becomes:

        magazine: carefully check check hope in properly sentence the this words you
    
        note: check check properly this words
    

    keep i = 0, j= 0,count = 0

    while loop(i < length of note , j < length of magazine):

    if note[i] == magazine[j] increase 'i' and 'count'; else do nothing
    
    but increase j every time you enter the loop
    

    if every word of note is in magazine, our count will be length of 'note' array, so we print 'yes' if count == l1; else the answer is 'no'

    using either 'i' or 'count' is enough, I used both to make code understandable.

    May be I didn't explain well, but this code worked for all test cases.