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

 

Learn to build Production-Ready Serverless applications

Want to learn how to build Serverless applications and follow best practices? Subscribe to my newsletter and join over 3,000 AWS & Serverless enthusiasts who have signed up already.
As a BONUS, you will receive early access and discount for my new AppSync course.

2 thoughts on “Ransom Note problem in F#”

  1. 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. 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 Comment

Your email address will not be published.