383. Ransom Note
Asked at 13Apple53Microsoft47Google40Amazon39Bloomberg37Meta35Anduril55Criteo78Karat76Tripadvisor70Spotify65SAP62tcs27
Problem
Decide whether ransomNote can be spelled with letters cut from magazine, using each letter of magazine at most once.
Example: ransomNote = "aa", magazine = "aab" → true; ransomNote = "aa", magazine = "ab" → false
Constraints: lowercase English letters.
Count the magazine's letters once; every letter of the note must be available that many times.
Complexity: O(m + n) time, O(1) space (26 letters).
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
have = Counter(magazine)
return all(have[c] >= k for c, k in Counter(ransomNote).items())
assert Solution().canConstruct("a", "b") is False
assert Solution().canConstruct("aa", "ab") is False
assert Solution().canConstruct("aa", "aab") is True
assert Solution().canConstruct("", "x") is True
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] cnt = new int[26];
for (char c : magazine.toCharArray()) cnt[c - 'a']++;
for (char c : ransomNote.toCharArray()) if (--cnt[c - 'a'] < 0) return false;
return true;
}
}
func canConstruct(ransomNote string, magazine string) bool {
var have [26]int
for _, c := range magazine {
have[c-'a']++
}
for _, c := range ransomNote {
if have[c-'a']--; have[c-'a'] < 0 {
return false
}
}
return true
}