Top Interview 150
The Ransom Note problem is a simple string manipulation challenge that tests your ability to manage character counts efficiently. Letβs solve LeetCode 383 step by step.
π Problem Description
Given two strings ransomNote
and magazine
:
- Return
true
ifransomNote
can be constructed using letters frommagazine
. - Each letter in
magazine
can only be used once inransomNote
.
π‘ Examples
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
π JavaScript Solution
We solve this problem by counting the occurrences of each letter in magazine
and comparing them with the required counts for ransomNote
.
Implementation
var canConstruct = function(ransomNote, magazine) {
const charCount = {};
for (let char of magazine) {
charCount[char] = (charCount[char] || 0) + 1;
}
for (let char of ransomNote) {
if (!charCount[char] || charCount[char] <= 0) {
return false;
}
charCount[char]--;
}
return true;
};
π How It Works
-
Count Characters in Magazine:
- Create a hash map (
charCount
) to store the frequency of each character inmagazine
.
- Create a hash map (
-
Validate Against Ransom Note:
- Iterate through each character in
ransomNote
. - Check if the character is available in
charCount
. - If not, return
false
. - Decrement the count of the character in
charCount
.
- Iterate through each character in
-
Return Result:
- If all characters are found with sufficient counts, return
true
.
- If all characters are found with sufficient counts, return
π Complexity Analysis
-
Time Complexity:
O(n+m)
, wheren
is the length of magazine andm
is the length of ransomNote.- Counting characters in magazine takes
O(n)
. - Validating ransomNote takes
O(m)
.
- Counting characters in magazine takes
Space Complexity:
O(k)
, wherek
is the number of unique characters inmagazine
.
π Dry Run
Input: ransomNote = "aa"
, magazine = "aab"
Output: true
β¨ Pro Tips for Interviews
-
Clarify Constraints:
- Ensure that
ransomNote
andmagazine
only contain lowercase letters. - Ask about edge cases, such as empty strings.
- Ensure that
-
Discuss Optimizations:
- Highlight how using a hash map ensures efficient character counting.
-
Edge Cases:
-
ransomNote
longer thanmagazine
β immediately returnfalse
. - All characters in
magazine
but insufficient counts.
-
π Learn More
Check out the full explanation and code walkthrough on my previous Dev.to post:
π Set Matrix Zeroes - JavaScript Solution
Whatβs your preferred method to solve this problem? Letβs discuss! π
Top comments (1)
Follow Me on GitHub π
If you found this solution helpful, check out more of my projects and solutions on my GitHub profile.
Don't forget to follow for more updates!