Published:
Updated:


Solution

import sys
from collections import deque 
n=int(sys.stdin.readline())
queue=deque()
for i in range(n):
    line = sys.stdin.readline().strip()
    if "push" in line:
        a,num=line.split()
        queue.append(num)
    elif line=="pop":
        if queue:
            print(queue.popleft())
        else:
            print(-1)
    elif line=="size":
        print(len(queue))
    elif line=="front":
        if queue:
            print(queue[0])
        else:
            print(-1)
    elif line=="back":
        if queue:
            print(queue[-1])
        else:
            print(-1) 
    elif line=="empty":
        if queue:
            print(0)
        else:
            print(1)


Timeout Solution

import collections
import sys
from typing import List


def solution(commands: List[List[str]]) -> List[int]:
    answer = []
    queue = collections.deque()

    for command in commands:
        x1, x2 = make_x1_x2(command)

        if x1 == 'push':
            queue.append(x2)
            continue

        if x1 == 'pop':
            if not queue:
                answer.append(-1)
                continue

            answer.append(queue.popleft())
            continue

        if x1 == 'size':
            answer.append(len(queue))
            continue

        if x1 == 'empty':
            if not queue:
                answer.append(1)
                continue

            answer.append(0)
            continue

        if x1 == 'front':
            if not queue:
                answer.append(-1)
                continue

            answer.append(queue[0])
            continue

        if x1 == 'back':
            if not queue:
                answer.append(-1)
                continue

            answer.append(queue[-1])
            continue

    return answer


def make_x1_x2(command):
    x1, x2 = '', ''
    if len(command) == 2:
        x1, x2 = command[0], command[1]
    else:
        x1 = command[0]
    return x1, x2


N = int(sys.stdin.readline().rstrip())
array = []
for _ in range(N):
    array.append(sys.stdin.readline().split())

print(*solution(array), sep='\n')

Leave a comment