link: https://leetcode.com/problems/reveal-cards-in-increasing-order/

Thought

So the rule is if you pop anything from front, then you shall move next head to tail. Reversely, if we want to build the original sequence, we could assume if you want to insert anything in head, you should pop your tail, and push the tail to head

Code

class Solution:
    def deckRevealedIncreasing(self, deck):
        """
        :type deck: List[int]
        :rtype: List[int]
        """
        deck.sort(reverse= True)
        res = collections.deque()
        for i in deck:
            if not res:
                res.append(i)
            else:
                p = res[-1]
                res.pop()
                res.appendleft(p)
                res.appendleft(i)
        return list(res)
            

Runtime

Time: O(n)
Space: O(n)

Leave a Reply