383. Ransom Note LeetCode Solution

In this guide, you will get 383. Ransom Note LeetCode Solution with the best time and space complexity. The solution to Ransom Note problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Ransom Note solution in C++
  4. Ransom Note solution in Java
  5. Ransom Note solution in Python
  6. Additional Resources
383. Ransom Note LeetCode Solution image

Problem Statement of Ransom Note

Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.
Each letter in magazine can only be used once in ransomNote.

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:

1 <= ransomNote.length, magazine.length <= 105
ransomNote and magazine consist of lowercase English letters.

Complexity Analysis

  • Time Complexity: O(|\texttt{ransomNote}| + |\texttt{magazine}|)
  • Space Complexity: O(26) = O(1)

383. Ransom Note LeetCode Solution in C++

class Solution {
 public:
  // Similar to 0242. Valid Anagram
  bool canConstruct(string ransomNote, string magazine) {
    vector<int> count(26);

    for (const char c : magazine)
      ++count[c - 'a'];

    for (const char c : ransomNote) {
      if (count[c - 'a'] == 0)
        return false;
      --count[c - 'a'];
    }

    return true;
  }
};
/* code provided by PROGIEZ */

383. Ransom Note LeetCode Solution in Java

class Solution {
  public boolean canConstruct(String ransomNote, String magazine) {
    int[] count = new int[26];

    for (final char c : magazine.toCharArray())
      ++count[c - 'a'];

    for (final char c : ransomNote.toCharArray()) {
      if (count[c - 'a'] == 0)
        return false;
      --count[c - 'a'];
    }

    return true;
  }
}
// code provided by PROGIEZ

383. Ransom Note LeetCode Solution in Python

class Solution:
  def canConstruct(self, ransomNote: str, magazine: str) -> bool:
    count1 = collections.Counter(ransomNote)
    count2 = collections.Counter(magazine)
    return all(count1[c] <= count2[c] for c in string.ascii_lowercase)
# code by PROGIEZ

Additional Resources

See also  732. My Calendar III LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.