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
.
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
Constraints:
1 <= ransomNote.length, magazine.length <= 10^5 ransomNote and magazine consist of lowercase English letters.
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
if (ransomNote.length() > magazine.length()) {
return false;
}
int[] magazineChars = new int[26];
for (char c : magazine.toCharArray()) {
magazineChars[c - 'a']++;
}
for (char c : ransomNote.toCharArray()) {
if (magazineChars[c - 'a'] == 0) {
return false;
}
magazineChars[c - 'a']--;
}
return true;
}
}
A naive approach would involve iterating through the ransomNote
and for each character, searching for it in magazine
. If found, remove it from magazine
and continue. If not found, return false
. This approach has a time complexity of O(m*n), where n is the length of ransomNote
and m is the length of magazine
.
The optimal solution involves using a frequency array (or HashMap) to count the occurrences of each character in the magazine
. Then, iterate through the ransomNote
and decrement the count for each character. If the count becomes negative, it means the magazine
does not have enough characters to construct the ransomNote
, so return false
. This approach has a time complexity of O(m + n), where n is the length of ransomNote
and m is the length of magazine
.
The time complexity of the provided solution is O(m + n), where n is the length of ransomNote
and m is the length of magazine
.
magazine
: The code iterates through the magazine
string once to count the frequency of each character. This loop takes O(m) time, where m is the length of the magazine
.ransomNote
: The code iterates through the ransomNote
string once to check if each character is available in the required quantity in the magazine
. This loop takes O(n) time, where n is the length of the ransomNote
.Since these two loops are performed sequentially, the overall time complexity is O(m + n).
The space complexity of the provided solution is O(1), which means it uses a constant amount of extra space regardless of the input size.
magazineChars
of size 26 to store the frequency of each lowercase English letter in the magazine
. Since the size of the array is fixed (26), it occupies a constant amount of space.Therefore, the overall space complexity is O(1).
ransomNote
longer than magazine
: If the ransomNote
is longer than the magazine
, it's impossible to construct the ransomNote
, so return false
immediately.ransomNote
or magazine
is an empty string, handle appropriately. If ransomNote
is empty, return true
. If magazine
is empty but ransomNote
is not, return false
.