• + 0 comments

    The O(1) solution is good. But it is just a matter of observing mathematics patterns, which I don't think it is good because we are practicing computer algorithm, rather than to guess match patterns. So my solution is computer-like and this is a more general approach to solving algorithm problems.

    def gameOfStones(n):
        tr = (n + 1) * [False]
        if n >= 1:
            tr[1] = False
        if n >= 2:
            tr[2] = True
        if n >= 3:
            tr[3] = True
        if n >= 4:
            tr[4] = True
        if n >= 5:
            tr[5] = True
        if n > 5:
            for i in range(6, n + 1):
                tr[i] = not tr[i - 2] or not tr[i - 3] or not tr[i - 5]
    
        if tr[n]:
            return "First"
        else:
            return "Second"