Yan Cui
I help clients go faster for less using serverless technologies.
This article is brought to you by
Don’t reinvent the patterns. Catalyst gives you consistent APIs for messaging, data, and workflow with key microservice patterns like circuit-breakers and retries for free.
A problem that has shown up multiple times in my preparation for technical interviews is the so called Ransom Note problem.
To solve this in F# is pretty simple.
In the interest of efficiency I decided to use a mutable Dictionary instead of the F# Map to store the no. of times a letter appears in the ransom note.
There’s also an optimization here to stop iterating through the magazine once all the letters for the ransom note is accounted for. One way to do it is to use Seq.takeWhile and mutate the Dictionary as we iterate through letters in the magazine, and stop when letters.Count = 0.
Try it Yourself
Links
- A Java implementation
- Interview question on CareerCup
- DotNetFiddle snippet
- All my Project Euler solutions in F#
- All my Advent of Code solutions in F#
Whenever you’re ready, here are 3 ways I can help you:
- Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop for quickly levelling up your serverless skills.
- I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.
- Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.
Can’t it be simpler to use Seq.countBy
let canConstruct ransomNote =
let letters = ransomNote |> Seq.countBy id |> Map.ofSeq
let valueOrDefault letter = defaultArg (Map.tryFind letter letters) 0
Seq.countBy id >> Seq.exists (fun (letter, count) -> count > valueOrDefault letter)
Or if you really want to not use a Map
let canConstruct ransomNote =
let letters = ransomNote |> Seq.countBy id |> dict
let valueOrDefault letter = match letters.TryGetValue letter with true, value -> value | _ -> 0
Seq.countBy id >> Seq.exists (fun (letter, count) -> count > valueOrDefault letter)
good shout, didn’t think of Seq.countBy at the time, it would make it simpler for counting up the letters in the ransomNote, you could do the same with the magazine article too and just check if the corresponding letter count in the magazine article is greater than the ransomNote.