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 <= 105ransomNote and magazine consist of lowercase English letters.This approach involves using hash maps to count the frequency of each letter in both ransomNote and magazine. The idea is to determine if magazine has enough of each letter to build ransomNote.
magazine.ransomNote and check if the magazine frequency is sufficient.ransomNote has a higher frequency than in magazine, return false.true.The solution uses an array count of size 26 to store the frequency of each character from 'a' to 'z'. It first increments the counts based on the characters in magazine and then decrements the respective counts as it encounters each character in ransomNote. If any count goes negative, it indicates that ransomNote cannot be formed, hence returning false.
C++
Java
Python
C#
JavaScript
Time Complexity: O(m + n), where m and n are the lengths of magazine and ransomNote, respectively.
Space Complexity: O(1), as the space is allocated for a fixed-size frequency array.
Instead of counting character frequencies, we can sort both ransomNote and magazine and use a two-pointer technique to check if magazine contains all letters needed for ransomNote in a sorted order.
ransomNote and magazine.ransomNote are matched, return true; otherwise, return false.This C solution sorts both strings using qsort and iterates using two indices, attempting to match each character from ransomNote with a character from magazine.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n log n + m log m), dominated by sorting
Space Complexity: O(1)
| Approach | Complexity |
|---|---|
| Approach 1: Frequency Counting with Hash Maps | Time Complexity: O(m + n), where m and n are the lengths of |
| Approach 2: Sorting and Two Pointers | Time Complexity: O(n log n + m log m), dominated by sorting |
Ransom note | Leetcode #383 • Techdose • 25,837 views views
Watch 9 more video solutions →Practice Ransom Note with our built-in code editor and test cases.
Practice on FleetCode