Ransom Note problem in F#

Yan Cui

I help clients go faster for less using serverless technologies.

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



Whenever you’re ready, here are 4 ways I can help you:

  1. 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.
  2. Do you want to know how to test serverless architectures with a fast dev & test loop? Check out my latest course, Testing Serverless Architectures and learn the smart way to test serverless.
  3. 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.
  4. Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.

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. Required fields are marked *