Ransom Note problem in F#

A prob­lem that has shown up mul­ti­ple times in my prepa­ra­tion for tech­ni­cal inter­views is the so called Ran­som Note prob­lem.

To solve this in F# is pret­ty sim­ple.

In the inter­est of effi­cien­cy I decid­ed to use a muta­ble Dic­tio­nary instead of the F# Map to store the no. of times a let­ter appears in the ran­som note.

There’s also an opti­miza­tion here to stop iter­at­ing through the mag­a­zine once all the let­ters for the ran­som note is account­ed for. One way to do it is to use Seq.takeWhile and mutate the Dic­tio­nary as we iter­ate through let­ters in the mag­a­zine, and stop when letters.Count = 0.


Try it Yourself