LeetCode 383: Ransom Note Solution
Master LeetCode problem 383 (Ransom Note), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
383. Ransom Note
Problem Explanation
Explanation
To solve this problem, we can iterate over the characters in the magazine string and count the frequency of each character. Then, we iterate over the characters in the ransomNote string and decrement the corresponding character count from the magazine map. If at any point the count goes negative or the character is not present in the map, we return false. If we are able to successfully construct the ransomNote using the characters from magazine, we return true.
Time Complexity
The time complexity of this approach is O(m + n), where m is the length of the magazine string and n is the length of the ransomNote string.
Space Complexity
The space complexity of this approach is O(1) since the frequency map will at most contain 26 lowercase English letters.
Solution Code
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] count = new int[26];
for (char c : magazine.toCharArray()) {
count[c - 'a']++;
}
for (char c : ransomNote.toCharArray()) {
if (count[c - 'a'] == 0) {
return false;
}
count[c - 'a']--;
}
return true;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 383 (Ransom Note)?
This page provides optimized solutions for LeetCode problem 383 (Ransom Note) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 383 (Ransom Note)?
The time complexity for LeetCode 383 (Ransom Note) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 383 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 383 in Java, C++, or Python.