[LeetCode] Min Stack

2025. 2. 26. 16:49·공부/코딩테스트 | 알고리즘

문제

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

Implement the MinStack class:

  • MinStack() initializes the stack object.
  • void push(int val) pushes the element val onto the stack.
  • void pop() removes the element on the top of the stack.
  • int top() gets the top element of the stack.
  • int getMin() retrieves the minimum element in the stack.

You must implement a solution with O(1) time complexity for each function.

 

예시

Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

Output
[null,null,null,null,-3,null,0,-2]

Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top();    // return 0
minStack.getMin(); // return -2

풀기

문제는 그냥 stack 구현하는 내용이다.

stack을 써도 되는건지 직접 다 구현하라는건가 했는데 좋은거 있는데 왜 안써? 마인드로 걍 씀.


결과

class MinStack() {
    private val stack = Stack<Int>()

    fun push(`val`: Int) {
        stack.push(`val`)
    }

    fun pop() {
        stack.pop()
    }

    fun top(): Int {
        return stack.peek()
    }

    fun getMin(): Int {
        return stack.min()
    }
}

 

위와 같이 풀었고 Accept 되었지만 GPT한테 이거 괜찮냐고 의견을 구해봄.

 

getMin 함수가 O(n) 복잡도를 가지니 더 최적화를 시켜 O(1) 복잡도로 변경시키자고 했음.

class MinStack() {
    private val stack = Stack<Int>()
    private val minStack = Stack<Int>() // 최소값을 저장하는 보조 스택

    fun push(`val`: Int) {
        stack.push(`val`)
        if (minStack.isEmpty() || `val` <= minStack.peek()) {
            minStack.push(`val`)
        }
    }

    fun pop() {
        if (stack.pop() == minStack.peek()) {
            minStack.pop() // 최소값이 사라지면 minStack에서도 제거
        }
    }

    fun top(): Int {
        return stack.peek()
    }

    fun getMin(): Int {
        return minStack.peek() // 최소값을 O(1) 시간에 반환
    }
}

 

위 코드가 GPT가 제안한 코드.

push 함수가 호출되면 minStack의 값을 확인해서 최솟값을 갱신.

pop 함수가 호출되면 그 값이 minStack 값과 비교해서 최솟값 삭제.

 

이렇게 하면 getMin 함수는 O(1) 복잡도가 된다.

 

GPT 짱~

'공부 > 코딩테스트 | 알고리즘' 카테고리의 다른 글

[LeetCode] Validate Binary Search Tree  (1) 2025.03.01
[LeetCode] Maximum Depth of Binary Tree  (0) 2025.02.27
[LeetCode] House Robber  (0) 2025.02.25
[LeetCode] Maximum Subarray  (0) 2025.02.24
[LeetCode] Climbing Stairs  (0) 2025.02.24
'공부/코딩테스트 | 알고리즘' 카테고리의 다른 글
  • [LeetCode] Validate Binary Search Tree
  • [LeetCode] Maximum Depth of Binary Tree
  • [LeetCode] House Robber
  • [LeetCode] Maximum Subarray
나는 유찌
나는 유찌
쩌리쨩
  • 나는 유찌
    유찌 개발 일기
    나는 유찌
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 사이드 프로젝트
        • 게시판
        • 블로그(Spring boot + React.js ..
      • 데이터베이스
        • SQLD
      • 이슈 해결
      • Front
        • Javascript
        • Vue.js
        • HTML+CSS
      • Backend
        • Spring
        • ORM
        • JAVA
      • 공부
        • HTTP
        • OOP
        • 이것저것
        • 코딩테스트 | 알고리즘
      • Computer Science
        • Computer architecture
        • 데이터베이스
        • 운영체제
      • 일상
        • 독서
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    phantom read
    Kotlin AntPathMatcher
    LeetCode
    Kotlin AccessDecisionManager
    JWT이란?
    AccessDecisionVoter
    role scope
    spring
    독서
    refresh token
    pessimisticlock
    권한 scope 처리
    Spring Boot
    mysql 격리수준
    Spring Security AccessDecisionManager
    웹 개발
    추리소설
    spring 격리수준
    jwt 로그인 구현
    DIRTY READ
    Access token 재발급
    AntPathMatcher
    jwt
    Access Token Refresh Token
    access token
    mssql
    Spring boot에서 JWT 구현
    redis 분산락
    한국소설
    히가시노 게이고
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
나는 유찌
[LeetCode] Min Stack
상단으로

티스토리툴바