Peeush Agarwal > Engineer. Learner. Builder.

I am a Machine Learning Engineer passionate about creating practical AI solutions using Machine Learning, NLP, Computer Vision, and Azure technologies. This space is where I document my projects, experiments, and insights as I grow in the world of data science.

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