Notes

Personal notes on various topics

View on GitHub

Intuition

To check if the ransom note can be constructed from the magazine, we need to ensure that every letter in the ransom note appears at least as many times in the magazine.

Approach

Complexity

Code

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        m_counts = {}
        for c in magazine:
            m_counts[c] = m_counts.get(c, 0) + 1

        for c in ransomNote:
            if c not in m_counts or m_counts[c] == 0:
                return False

            m_counts[c] -= 1

        return True

Back to Problem Statement