Problem:
Score: 500 points

Problem Statement

N people are standing in a queue, numbered 1, 2, 3, ..., N from front to back. Each person wears a hat, which is red, blue, or green.

The person numbered i says:

"In front of me, exactly A_i people are wearing hats with the same color as mine."

Assuming that all these statements are correct, find the number of possible combinations of colors of the N people's hats.

Since the count can be enormous, compute it modulo 1000000007.

Constraints

1 \leq N \leq 100000

0 \leq A_i \leq N-1

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 A_3 ... A_N

Output

Print the number of possible combinations of colors of the N people's hats, modulo 1000000007.

Sample Input 1

6
0 1 2 3 4 5

Sample Output 1

3

We have three possible combinations, as follows:

Red, Red, Red, Red, Red, Red

Blue, Blue, Blue, Blue, Blue, Blue

Green, Green, Green, Green, Green, Green

Sample Input 2

3
0 0 0

Sample Output 2

6

Sample Input 3

54
0 0 1 0 1 2 1 2 3 2 3 3 4 4 5 4 6 5 7 8 5 6 6 7 7 8 8 9 9 10 10 11 9 12 10 13 14 11 11 12 12 13 13 14 14 15 15 15 16 16 16 17 17 17

Sample Output 3

115295190

Solution in PyPy3 (2.4.0) (judge verdict: Runtime Error)

import numpy as np
from collections import defaultdict
import bisect

M = 1000000007
N = int(input())
left = list(map(int, input().split()))

indices = defaultdict(list)
for i, x in enumerate(left):
    indices[x].append(i)


def dp(t, n1, n2, n3):
    remaining = n1 + n2 + n3
    if remaining < 0:
        return 0
    cached = t[n1][n2][n3]
    if cached is not None:
        return cached
    last_cnt = left[remaining - 1] + 1
    res = 0
    if last_cnt == n1:
        res += dp(t, n1 - 1, n2, n3)
        res %= M
    if last_cnt == n2:
        res += dp(t, n1, n2 - 1, n3)
        res %= M
    if last_cnt == n3:
        res += dp(t, n1, n2, n3 - 1)
        res %= M
    # print(f"{remaining}: ({n1},{n2},{n3}) => {res}")
    t[n1][n2][n3] = res
    return res


def solve():
    heads = [0, 0, 0]
    for i in range(N):
        k = len(indices[i])
        if k == 3:
            heads[0] = heads[1] = heads[2] = i + 1
        elif k == 2:
            heads[0] = heads[1] = i + 1
        elif k == 1:
            heads[0] = i + 1
        else:
            break
    t = [
        [[None] * (heads[2] + 1) for _ in range(heads[1] + 1)]
        for _ in range(heads[0] + 1)
    ]
    t[0][0][0] = 1
    num_colors = len(indices[0])
    base = dp(t, heads[0], heads[1], heads[2])
    if len(indices[0]) < 3:
        return 3 * base
    else:
        return base


print(solve())