Introduction
The Ransom Note problem involves checking whether one string can be constructed using characters from another string.
Given:
- a string ransomNote
- a string magazine
the task is to determine whether:
- every character of ransomNote
can be formed using characters from magazine
Each character in magazine can only be used once.
This problem helps in understanding:
- hashing
- frequency counting
- string traversal
- resource allocation logic
Example
Input:ransomNote = "code"
magazine = "ocedxyz"
Output:
True
Explanation:
All characters required for "code"
are present in magazine.
Input: ransomNote = "hello"
magazine = "helo"
Output: False
Explanation:
Character 'l' is required twice
but appears only once.
Constraints
1 <= ransomNote.length,magazine.length <= 10^5
ransomNote and magazine
contain lowercase English letters
Approach 1 : Brute Force
Explanation
The simplest way to solve this problem is:
- Traverse ransomNote characters
- Search matching character inside magazine
- Mark used characters
This approach works but repeated searching increases time complexity.
Steps
- Convert magazine into list.
- Traverse ransomNote characters.
- Search matching character in magazine.
- Mark character as used.
- If any character is missing:
- return false
- Otherwise:
- return true
Dry Run
Input:ransomNote = "code"magazine = "ocedxyz"Check c:
Found in magazine
Mark as used
Check o: Found in magazine
Check d:
Found in magazine
Check e:
Found in magazine
Final Result: True
Brute Force Code
Complexity Analysis
Time Complexity: O(n²)Explanation:Repeated searching is performed
for every character.
Space Complexity: O(n) Explanation:
Extra storage may be used for traversal.
Approach 2 : Optimized Solution (Hashing)
Explanation
The optimized solution uses frequency counting.
The idea is:
- Count magazine character frequencies
- Reduce frequencies using ransomNote
- If any frequency becomes negative:
- construction is impossible
This avoids repeated searching.
Steps
- Create frequency hashmap.
- Count magazine characters.
- Traverse ransomNote.
- Reduce frequencies.
- If frequency becomes negative:
- return false
- Otherwise:
- return true
Dry Run
Input:ransomNote = "code"magazine = "ocedxyz"
Store frequencies:
o → 1
c → 1
e → 1
d → 1
Process ransomNote: c → decrease frequency
o → decrease frequency
d → decrease frequency
e → decrease frequency
All frequencies valid
Final Result:
True
Optimized Code
Complexity Analysis
Time Complexity: O(n)Explanation:Characters are processed once.
Space Complexity: O(n) Explanation:
Extra hashmap is used for frequencies.