# LeetCode 532. K-diff Pairs in an Array in F#

# Solve Daily LeetCode problem on 2022/02/09

Shohei Yoshida

## URL

https://leetcode.com/problems/k-diff-pairs-in-an-array/

## Code

https://github.com/syohex/dotnet-study/blob/master/fsharp/leetcode/problems/0532/main.fsx

let toMap (nums: int list) : Map<int, int> =

let rec toMap' nums m =

match nums with

| [] -> m

| head :: tail ->

match Map.tryFind head m with

| Some v -> toMap' tail (Map.add head (v + 1) m)

| None -> toMap' tail (Map.add head 1 m)

toMap' nums Map.empty

let findPairs (nums: int list) (k: int) : int =

let rec findPairs' keys k m acc =

match keys with

| [] -> acc

| head :: tail ->

match Map.tryFind (head - k) m with

| None -> findPairs' tail k m acc

| Some v ->

if k = 0 then

if v >= 2 then

findPairs' tail k m (acc + 1)

else

findPairs' tail k m acc

else

findPairs' tail k m (acc + 1)

let m = toMap nums

findPairs' (m |> Map.keys |> Seq.toList) k m 0

Upvote

Shohei Yoshida

A Programmer

Related Articles