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
.
ransomNote
is empty, return true
because it trivially requires no letters.magazine
.ransomNote
and check if each character is available in the frequency count constructed from magazine
.ransomNote
cannot be matched against the frequency count derived from magazine
, return false
.ransomNote
can be matched while respecting their frequencies, return true
.n
is the length of ransomNote
and m
is the length of magazine
.public class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] charCount = new int[26]; // Frequency array for letters 'a' to 'z'
// Populate the frequency array with counts from magazine
for (char c : magazine.toCharArray()) {
charCount[c - 'a']++;
}
// Check each character in ransomNote
for (char c : ransomNote.toCharArray()) {
if (--charCount[c - 'a'] < 0) {
return false; // If usage of any character exceeds its availability
}
}
return true; // All characters are available with sufficient frequency
}
}
charCount
array is used to store the count of each character in the magazine
. Since there are 26 lowercase English letters, the array size is 26.ransomNote
, we decrement the corresponding count in charCount
.magazine
, hence we return false
.ransomNote
without finding any character overused, we return true
.This approach ensures an efficient determination of whether ransomNote
can be constructed from magazine
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?