Problem overview
The method canConstruct receives two strings, ransomNote and magazine. It returns true if the note can be built from letters of the magazine, where each magazine letter can be used only once, and false otherwise.
With ransomNote = "aa" and magazine = "abb" the answer is false: the note needs two as and the magazine has one. With magazine = "aab" the answer is true.
The statement asks for O(n + m) time and extra space proportional to the alphabet size, which is a fixed constant.
Approach: compare letter counts
The order of letters in either string doesn't matter. The note "abba" and the note "aabb" need the same letters, and so do the magazines "aaabbb" and "ababab". What matters is how many times each letter occurs. The note can be built exactly when, for every letter, the magazine has at least as many copies as the note.
So count the letters of each string into a dictionary, then compare the counts letter by letter. Searching the magazine for each note letter and crossing it off would take O(n * m) time, and the counting approach reads each string once.
For "abba" and "ababab", the note needs a: 2, b: 2 and the magazine has a: 3, b: 3. Every needed count is covered, so the answer is true.
Counting both strings is also what makes the repeated-letter case work. A note that needs three as is only satisfied by a magazine with at least three, and the comparison catches that without any bookkeeping about which magazine letters have been used.
Step by step
- Create two dictionaries,
ransomFreqandmagazineFreq, both of type[Character: Int], mapping each character to how often it occurs. They arevar, since they are filled in. - Count the note. Loop
for c in ransomNote. AStringis a sequence ofCharactervalues, so the loop visits one character at a time. - Increment with a default.
ransomFreq[c, default: 0] += 1treats a letter that isn't in the dictionary yet as 0, so no existence check is needed. - Count the magazine the same way into
magazineFreq. Reusing the namecis fine, because each loop variable exists only inside its own loop. - Walk the alphabet. A loop over
charCodein97...122, the codes ofatoz. The closed range includes both ends. - Convert the code to a character.
Character(UnicodeScalar(charCode)!)givesc.UnicodeScalar(_:)is failable because not every integer is a valid scalar, so the result is force-unwrapped. For 97 through 122 it always succeeds. - Compare the counts. A plain dictionary subscript returns an optional, and
?? 0makes a missing letter count as 0. If the note needs more of the letter than the magazine has, returnfalse. - Return
true. Reaching the end means every letter had enough copies.
The solution in Swift
class Solution {
func canConstruct(_ ransomNote: String, _ magazine: String) -> Bool {
var ransomFreq: [Character: Int] = [:]
var magazineFreq: [Character: Int] = [:]
for c in ransomNote {
ransomFreq[c, default: 0] += 1
}
for c in magazine {
magazineFreq[c, default: 0] += 1
}
for charCode in 97...122 {
let c = Character(UnicodeScalar(charCode)!)
if (ransomFreq[c] ?? 0) > (magazineFreq[c] ?? 0) {
return false
}
}
return true
}
}
Swift details worth knowing:
- Characters. The dictionary keys are
Charactervalues, notStringvalues. In Swift, aStringcan't be indexed by integers, but iterating it withfor c inworks naturally. - The
default:subscript can both read and write.dict[c, default: 0] += 1reads the value (or 0), adds one and stores the result. - Optional comparison.
ransomFreq[c]is anInt?. Comparing optionals with>isn't allowed, which is why both sides are unwrapped with?? 0. - The parentheses around each
?? 0expression aren't strictly required, because??binds tighter than comparison operators, but they make the intent clear at a glance. - Range of integers.
97...122is aClosedRange<Int>. Writing97..<122would stop beforez. - The alphabet only. The check covers lowercase
atoz. Characters outside that range, such as capitals, digits or spaces, are counted but never compared, so this version suits inputs made of lowercase letters. To handle any character, loop over the keys ofransomFreqinstead.
Complexity
Time: O(n + m), where n is the length of the note and m the length of the magazine. Each string is read once, and the final loop always runs 26 times.
Space: O(Σ), where Σ is the alphabet size. Each dictionary holds at most one entry per distinct letter, which is at most 26 for lowercase text.
Edge cases and common mistakes
- Empty note. It needs nothing, so
canConstruct("", "abc")istrue. - Empty magazine.
canConstruct("abc", "")isfalse. - Letters used twice. Checking only that each note letter appears in the magazine would say
truefor"aa"and"abb". The counts are what matter. - Comparing in the wrong direction. The note's count must not exceed the magazine's. A magazine may have extra letters.
- Forgetting
?? 0. A letter missing from a dictionary isnil, and comparing it as a number doesn't compile. - Crashing on a missing key. Force-unwrapping with
!where a key may be absent stops the program. - Letters outside
atoz. This version doesn't compare them.
Testing
"aa"and"abb"givefalse."aa"and"aab"givetrue."abba"and"ababab"givetrue.""and"abc"givetrue, and"abc"and""givefalse.
