Ransom Note

Can `ransomNote` be built from `magazine`'s letters? Letter-count subset check.

Easy
Time O(N + M) Space O(1)
LeetCode
2 min read
hash-map counting strings

Problem#

Given ransomNote and magazine, return true iff every letter in ransomNote is available in magazine with at least its required multiplicity (each magazine letter usable once).

Examples#

  • ransomNote = "a", magazine = "b"false.
  • ransomNote = "aa", magazine = "aab"true.

Constraints#

  • 1 <= ransomNote.length, magazine.length <= 10^5, lowercase.

Hints#

Hint
Counter from magazine; decrement on each ransom letter, fail if it goes negative.

Approach#

Count magazine letters. For each character in ransomNote, decrement; if any drops below zero, return false.

Solution#

Ransom Note
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int cnt[26] = {0};
for (char c : magazine) ++cnt[c - 'a'];
for (char c : ransomNote) {
if (--cnt[c - 'a'] < 0) return false;
}
return true;
}
};

Editorial#

Magazine letters are consumable: each one in the counter supports exactly one ransom letter. Failure is purely a negative-count check, so the loop bails the moment we run out.

Complexity#

  • Time: O(N + M).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.