본문 바로가기

Study/Coding Test

[BaekJoon] 큐(JavaScript)

📘 오늘의 코딩테스트 - 큐(JavaScript)

🔢 문제 번호: 10845번

🔗 문제 링크: 백준 - 큐

 

 

 

 

🧠 문제 요약

  • 정수를 저장하는 큐를 구현하고, 입력으로 주어지는 명령어를 처리하는 문제
  • 규는 FIFO(First In,m First Out) 구조로 먼저 들어간 것이 먼저 나온다
  • 명령어: push X, pop, size, empty, front, back
    • 입력: 첫째 줄에 명령의 수 N, 둘째 줄부터 N개의 명령
    • 출력: 출력해야 하는 명령이 주어질 때마다 한 줄에 하나씩 출력

 

 

 

✅ 실행 예시 및 결과

입력:
15
push 1
push 2
front
back
size
empty
pop
pop
pop
size
empty
pop
push 3
empty
front

출력:
1
2
2
0
1
2
-1
0
1
-1
0
3

 

 

 

✍️ 내 풀이

  • javascript 배열을 큐로 사용하되, front 인덱스로 성능 최적화
  • switch 문으로 각 명령어별 동작 처리
  • 출력을 result 배열에 모아서 join('\n')으로 한 번에 처리

 

 

 

💻 내가 푼 코드

const input = require("fs")
  .readFileSync("/dev/stdin", "utf8")
  .trim()
  .split("\n");

const [N, ...commands] = input;

// 큐 역할을 할 배열
const queue = [];
// 큐의 실제 시작점을 가리키는 인덱스
let front = 0;
// 출력할 결과물 배열
const result = [];

for (let i = 0; i < N; i++) {
  // 명령어를 공백으로 분리
  const command = commands[i].split(" ");

  // 첫 번째 단어로 명령어 종류 구분
  switch (command[0]) {
    // 큐 뒤쪽에 요소 추가
    case "push":
      queue.push(command[1]);
      break;
    case "pop":
      // 큐가 비어있는지 확인 (전체 길이 - front 인덱스)
      if (queue.length - front === 0) {
        result.push(-1);
      } else {
        // front 위치의 요소 출력
        result.push(queue[front]);
        // front 인덱스를 앞으로 이동
        front++;
      }
      break;
    case "size":
      // 현재 큐의 실제 크기 (전체 길이 - 제거된 요소 개수)
      result.push(queue.length - front);
      break;
    case "empty":
      // 큐가 비어있으면 1, 아니면 0
      result.push(queue.length - front === 0 ? 1 : 0);
      break;
    case "front":
      // 큐의 맨 앞 요소 확인
      result.push(queue.length - front === 0 ? -1 : queue[front]);
      break;
    case "back":
      // 큐의 맨 뒤 요소 확인 (항상 배열의 마지막 요소)
      result.push(queue.length - front === 0 ? -1 : queue[queue.length - 1]);
      break;
  }
}

console.log(result.join("\n"));

 

 

 

📎 남이 푼 코드

class Queue {
    constructor() {
        this.items = [];
        this.front = 0;
        this.rear = 0;
    }
    
    push(item) {
        this.items[this.rear++] = item;
    }
    
    pop() {
        if(this.front === this.rear) return -1;
        return this.items[this.front++];
    }
    
    size() {
        return this.rear - this.front;
    }
    
    empty() {
        return this.front === this.rear ? 1 : 0;
    }
    
    getFront() {
        return this.front === this.rear ? -1 : this.items[this.front];
    }
    
    getBack() {
        return this.front === this.rear ? -1 : this.items[this.rear - 1];
    }
}
  • 클래스로 큐를 직접 구현하여 메모리 효율성 향상
  • front와 rear 인덱스로 큐의 시작과 끝을 관리
  • 실제 요소 삭제 없이 인덱스만 이동하여 성능 최적화
  • 코드가 길어지고 복잡도가 증가하지만 대용량 데이터에서 유리
  • 실제 개발에서는 간결하고 직관적인 함수형 접근이 더 트렌드

 

 

 

🔍 회고 & 배운 점

  • 자료구조 큐의 기본원리(FIFO)를 구현해볼 수 있었다
  • 처음에는 직관적인 shift() 방식을 사용했지만 시간초과로 실패!!
  • switch문에서 case 별로 console.log를 하면 이것도 시간초과!!
  • join()으로 한번에 모아서 출력하는게 더 빠르다!!

 

반응형

'Study > Coding Test' 카테고리의 다른 글

[BaekJoon] 듣보잡(JavaScript)  (1) 2025.08.30
[BaekJoon] 요세푸스 문제 0(JavaScript)  (4) 2025.08.28
[BaekJoon] 스택(JavaScript)  (1) 2025.08.26
[BaekJoon] 숫자 카드2(JavaScript)  (1) 2025.08.25
[baekjoon] 괄호(JavaScript)  (0) 2025.08.23