program main
    use,intrinsic :: iso_fortran_env
    implicit none
    integer(int64):: i,n,ans=1
    integer(int64),parameter:: md = 1000000007
    integer(int64), allocatable:: a(:)

    read*, n
    allocate(a(n))
    read*, a(:)

    block; integer:: i1=0, i2=0, i3=0
        do i=1,n
            if (i1 == i2 .and. i2 == i3) then
                ans=mod(ans*3, md)
                i1=i1+1
            else if (i1 == i2 .and. a(i) == i1) then
                ans=mod(ans*2, md)
                i1=i1+1
            else if (i2 == i3 .and. a(i) == i2) then
                ans=mod(ans*2, md)
                i2=i2+1
            else
                if (a(i) == i1) then
                    i1=i1+1
                else if(a(i) == i2) then
                    i2=i2+1
                else
                    i3=i3+1
                end if
            end if
        end do
    end block
    print'(i0)', ans
end program main