Skip to content

Instantly share code, notes, and snippets.

@ak9999
Last active March 5, 2021 02:26
Show Gist options
  • Save ak9999/d354aa62cf02e35500421b31f0b31a3a to your computer and use it in GitHub Desktop.
Save ak9999/d354aa62cf02e35500421b31f0b31a3a to your computer and use it in GitHub Desktop.
Mob programming solutions to the Ransom Note problem from Leetcode: https://leetcode.com/problems/ransom-note/
Link: https://leetcode.com/problems/ransom-note/
Given an arbitrary ransom note string and another string containing letters from all the magazines,
write a function that will return true if the ransom note can be constructed from the magazines;
otherwise, it will return false.
Each letter in the magazine string can only be used once in your ransom note.
Example 1:
Input: ransomNote = "a", magazine = "b"
Output: false
Example 2:
Input: ransomNote = "aa", magazine = "ab"
Output: false
Example 3:
Input: ransomNote = "aa", magazine = "aab"
Output: true
Constraints:
You may assume that both strings contain only lowercase letters.
from collections import Counter
def ransom_note(string1, string2):
note = Counter(string1)
magazine = Counter(string2)
for key, value in note.items():
if value > magazine[key]:
return False
return True
def ransom_note(string1, string2):
chars = set(string1)
for c in chars:
needed = string1.count(c)
if string2.count(c) < needed:
return False
return True
from solution import ransom_note
def test_single_letter():
assert ransom_note('a', 'b') == False
def test_one_letter_difference():
assert ransom_note("aa", "aab") == True
def test_two_letter_difference():
assert ransom_note('aac', 'aabbc') == True
def test_partial_anagram():
assert ransom_note('anna', 'banana') == True
def test_anagram():
assert ransom_note('elevenplustwo', 'twelveplusone') == True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment