LeetCode 946. Validate Stack Sequences in F#

URL

Validate Stack Sequences - LeetCode

Code

https://github.com/syohex/dotnet-study/tree/master/fsharp/leetcode/challenge/202304/validate_stack_sequences/main.fsx

let validateStackSequences (pushed: int list) (popped: int list) : bool =
    let rec validateStackSequences' pushed popped stack =
        match pushed, popped with
        | [], [] -> true
        | _, [] -> failwith "never reach here"
        | [], h :: t ->
            match stack with
            | [] -> failwith "never reach here"
            | h2 :: t2 ->
                if h = h2 then
                    validateStackSequences' pushed t t2
                else
                    false
        | h1 :: t1, h2 :: t2 ->
            match stack with
            | [] -> validateStackSequences' t1 popped (h1 :: stack)
            | h3 :: t3 ->
                if h2 = h3 then
                    validateStackSequences' pushed t2 t3
                else
                    validateStackSequences' t1 popped (h1 :: stack)

    validateStackSequences' pushed popped []