Ransom Note problem in F#

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

2 Comments

  1. Sehnsucht   •  

    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)

  2. Yan Cui   •  

    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.

Leave a Reply

Your email address will not be published.