383. Ransom Note ๐
Difficulty: Easy
- Tags: Hash Table
, String
Problem Statement ๐
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
.
Examples ๐
๐น Example 1:
Input:
Output:
๐น Example 2:
Input:
Output:
๐น Example 3:
Input:
Output:
Constraints โ๏ธ
1 <= ransomNote.length, magazine.length <= 10^5
ransomNote
andmagazine
consist of lowercase English letters.
Solution ๐ก
To solve this problem, we can use a hash map to count the occurrences of each character in magazine
. Then, we check if each character in ransomNote
can be satisfied using the character counts.
Java Solution
Explanation of the Solution
Count Characters in Magazine:
Use a
HashMap
to store the frequency of each character inmagazine
.
Validate Ransom Note:
Iterate through
ransomNote
and check if the required character is available in theHashMap
with a count greater than 0.If available, decrement the count. If not, return
false
.
Result:
If all characters in
ransomNote
are satisfied, returntrue
.
Time Complexity โณ
O(m + n):
m
is the length ofransomNote
.n
is the length ofmagazine
.Both strings are traversed once.
Space Complexity ๐พ
O(k):
k
is the number of unique characters inmagazine
.Space used by the
HashMap
.
Last updated