<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://melonicedlatte.com/feed.xml" rel="self" type="application/atom+xml" /><link href="https://melonicedlatte.com/" rel="alternate" type="text/html" /><updated>2025-11-23T03:29:32+09:00</updated><id>https://melonicedlatte.com/feed.xml</id><title type="html">Easy is Perfect</title><subtitle>Want to make some good product for world with programming. I want to learn many things and i love learn something new!
</subtitle><author><name>melonicedlatte</name><email>melonicedlatte@gmail.com</email></author><entry><title type="html">[AWS] 다른 계정 or Region 에 이벤트가 발생했을 때, EventBridge 로 Event 전달하기</title><link href="https://melonicedlatte.com/2023/11/23/131900.html" rel="alternate" type="text/html" title="[AWS] 다른 계정 or Region 에 이벤트가 발생했을 때, EventBridge 로 Event 전달하기" /><published>2023-11-23T00:00:00+09:00</published><updated>2023-11-23T00:00:00+09:00</updated><id>https://melonicedlatte.com/2023/11/23/131900</id><content type="html" xml:base="https://melonicedlatte.com/2023/11/23/131900.html"><![CDATA[<h2 id="1-problem">1. Problem</h2>

<ul>
  <li>AWS 에서는 서비스 Region 을 지정하여 서비스를 운영할 수 있습니다.</li>
  <li>서비스들에서 발생한 Event 들은 EventBridge 를 통하여 다른 Event 를 Trigger 할 수 있습니다.</li>
  <li>어떤 Region 에서 에러가 발생했을 때, 이와 다른 Region 에서 이 이벤트를 확인하여 처리하고 싶을 수 있습니다.
    <ul>
      <li>예를 들어, AWS 서비스 중에서는 <code class="language-plaintext highlighter-rouge">글로벌</code> 서비스로 운영되는 서비스들의 일부 Event 들이 Default 로 <code class="language-plaintext highlighter-rouge">미국 동부 (버지니아 북부) us-east-1</code> 로 전송됩니다.</li>
      <li>서비스가 서울에서 운영되고 있어도 이벤트가 미국 동부로 전달되기 때문에, 미국 동부에서 이벤트를 잡아서 서울로 보내서 처리해야합니다.</li>
    </ul>
  </li>
  <li>이런 상황에서 이슈를 처리하려면 어떻게 해야할까요?</li>
</ul>

<h2 id="2-solution">2. Solution</h2>

<ul>
  <li>방법은 바로 EventBridge 의 대상(Target)을 다른 region 에 있는 EventBridge 로 정하는 것입니다.</li>
  <li>아래의 이미지와 같이 EventBridge 의 대상에 <code class="language-plaintext highlighter-rouge">다른 계정 또는 리전의 이벤트 버스</code> 를 지정할 수 있습니다.</li>
  <li>다른 지역의 ARN 정보를 입력한 후 등록하면 Event 가 발생했을 때, 정상적으로 Event 를 전달해줍니다.
    <ul>
      <li>예를 들어, 이렇게 동작할 수 있습니다.
        <ul>
          <li>미국에서 이벤트 발생 -&gt; 미국 EventBridge 가 Event 감지 후 한국 EventBridge 호출 -&gt; EventBridge 가 Event 감지 후 Trigger 발동(ex, lambda, sqs, sns 등)</li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

<p><img src="/assets/images/2022/2023-11-23-13-53-50.png" alt="image" class="rounded img_center border_2em" /></p>]]></content><author><name>melonicedlatte</name></author><category term="Aws" /><summary type="html"><![CDATA[1. Problem AWS 에서는 서비스 Region 을 지정하여 서비스를 운영할 수 있습니다. 서비스들에서 발생한 Event 들은 EventBridge 를 통하여 다른 Event 를 Trigger 할 수 있습니다. 어떤 Region 에서 에러가 발생했을 때, 이와 다른 Region 에서 이 이벤트를 확인하여 처리하고 싶을 수 있습니다. 예를 들어, AWS 서비스 중에서는 글로벌 서비스로 운영되는 서비스들의 일부 Event 들이 Default 로 미국 동부 (버지니아 북부) us-east-1 로 전송됩니다. 서비스가 서울에서 운영되고 있어도 이벤트가 미국 동부로 전달되기 때문에, 미국 동부에서 이벤트를 잡아서 서울로 보내서 처리해야합니다. 이런 상황에서 이슈를 처리하려면 어떻게 해야할까요? 2. Solution 방법은 바로 EventBridge 의 대상(Target)을 다른 region 에 있는 EventBridge 로 정하는 것입니다. 아래의 이미지와 같이 EventBridge 의 대상에 다른 계정 또는 리전의 이벤트 버스 를 지정할 수 있습니다. 다른 지역의 ARN 정보를 입력한 후 등록하면 Event 가 발생했을 때, 정상적으로 Event 를 전달해줍니다. 예를 들어, 이렇게 동작할 수 있습니다. 미국에서 이벤트 발생 -&gt; 미국 EventBridge 가 Event 감지 후 한국 EventBridge 호출 -&gt; EventBridge 가 Event 감지 후 Trigger 발동(ex, lambda, sqs, sns 등)]]></summary></entry><entry><title type="html">[Spring Boot] WebFlux란? reactive, 반응형 프로그래밍 개념정리</title><link href="https://melonicedlatte.com/2023/11/21/110300.html" rel="alternate" type="text/html" title="[Spring Boot] WebFlux란? reactive, 반응형 프로그래밍 개념정리" /><published>2023-11-21T00:00:00+09:00</published><updated>2023-11-21T00:00:00+09:00</updated><id>https://melonicedlatte.com/2023/11/21/110300</id><content type="html" xml:base="https://melonicedlatte.com/2023/11/21/110300.html"><![CDATA[<h2 id="1-webflux란">1. WebFlux란?</h2>

<h3 id="11-webflux-가-생긴-이유">1.1 WebFlux 가 생긴 이유</h3>
<ul>
  <li>기존 스프링 프레임워크는 Servlet API와 Servlet 컨테이너로 이루어졌고, 동기적으로 요청을 처리함.</li>
  <li><code class="language-plaintext highlighter-rouge">기존 Spring MVC는 하나의 요청에 대해 하나의 스레드</code>가 사용된다
    <ul>
      <li><strong>thread:request(1:1), sync + blocking 방식</strong></li>
      <li>스레드 생성에는 시간이 걸리기 때문에, 다수의 요청을 고려하여 미리 스레드 풀을 생성해놓는다.</li>
      <li>또한, 스레드는 컨텍스트 스위칭 비용이 발생한다.</li>
      <li>기존에는 하나의 요청마다 하나의 스레드를 할당하여 처리했다.</li>
    </ul>
  </li>
  <li>MSA 환경에서 한 서비스가 다수의 다른 서비스들에게 요청하고 결과를 기다릴 때 까지 스레드를 점유하면, 스레드가 계속해서 사용되고 있는 상황이 유지된다. 따라서, 다수의 유저에게 응답해줄 수 없다.</li>
  <li>이러한 문제로 인하여 <strong>적은 양의 스레드와 최소한의 하드웨어 자원으로 동시성을 핸들링</strong>하기 위해 만들어졌다.</li>
  <li>단일 스레드에서 Blocking I/O 와 Non-Blocking I/O 를 비교하면 아래와 같습니다.</li>
</ul>

<p><img src="/assets/images/2022/2023-11-21-12-10-06.png" alt="image" class="rounded img_center border_2em" /></p>

<h3 id="12-webflux-특징">1.2. WebFlux 특징</h3>

<ul>
  <li>WebFlux 는 이를 <code class="language-plaintext highlighter-rouge">리액티브 프로그래밍 방식을 사용</code>하여 <code class="language-plaintext highlighter-rouge">논블로킹과 고정된 스레드로 모든 요청을 처리</code>하여 기존의 문제를 해결한다.
    <ul>
      <li><strong>thread:many_request(1:N), async + nonblocking 방식</strong></li>
    </ul>
  </li>
  <li>Spring Framwork5에서 새롭게 추가된 모듈이며 reactive 스타일의 어플리케이션 개발을 도와준다
    <ul>
      <li><strong>reactive 란?</strong>
        <ul>
          <li>reactive란 <strong>반응형 프로그래밍으로 변화에 반응하게 만들어진 프로그래밍 모델</strong></li>
          <li>반응형 프로그래밍은 <strong>데이터 스트림을 처리하며 이 데이터 스트림이 변경될 때마다 반응</strong></li>
          <li>기존에 사용하던 명령형 프로그래밍의 경우는 컴퓨터가 수행해야 하는 일을 순서대로 처리</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>WebFlux 는 <code class="language-plaintext highlighter-rouge">반응형 프로그래밍(Reactive Programming)</code> 방식을 통해 <code class="language-plaintext highlighter-rouge">Event-Driven(이벤트 기반)의 비동기식 애플리케이션</code>을 구축</li>
  <li>reactive-stack web framework이며 non-blocking에 Reactive stream 지원</li>
  <li>반응형 스트림(Reactive Stream)에서 Publisher-Subscriber 패턴을 사용
    <ul>
      <li>Publisher는 데이터를 생성하고 Subscriber는 이를 처리</li>
      <li>이벤트 스트림에 있는 데이터를 Subscriber가 비동기적으로 가져옴</li>
    </ul>
  </li>
  <li>tomcat이 아닌 netty 같은 <strong>async, non-blocking 서버</strong> 사용
    <ul>
      <li>webflux Non-Blocking Request을 수행 중에 결과가 반환되지 않더라도 다른 작업 수행 가능</li>
    </ul>
  </li>
  <li>동기 프로그래밍과 비교하여 디버깅이 어려움</li>
  <li>비동기 소스코드 안에 동기 코드가 있으면, 비동기로 동작하지 않을 수 있어 주의 필요</li>
  <li>서비스간 호출이 많은 마이크로서비스 아키텍처에 적합</li>
</ul>

<hr />

<p><strong><em>reference</em></strong></p>

<ul>
  <li>https://heeyeah.github.io/spring/2020-02-29-web-flux/</li>
  <li>https://adjh54.tistory.com/232</li>
  <li>https://devmoony.tistory.com/174</li>
  <li>https://techblog.woowahan.com/2667/</li>
</ul>]]></content><author><name>melonicedlatte</name></author><category term="Web" /><summary type="html"><![CDATA[1. WebFlux란? 1.1 WebFlux 가 생긴 이유 기존 스프링 프레임워크는 Servlet API와 Servlet 컨테이너로 이루어졌고, 동기적으로 요청을 처리함. 기존 Spring MVC는 하나의 요청에 대해 하나의 스레드가 사용된다 thread:request(1:1), sync + blocking 방식 스레드 생성에는 시간이 걸리기 때문에, 다수의 요청을 고려하여 미리 스레드 풀을 생성해놓는다. 또한, 스레드는 컨텍스트 스위칭 비용이 발생한다. 기존에는 하나의 요청마다 하나의 스레드를 할당하여 처리했다. MSA 환경에서 한 서비스가 다수의 다른 서비스들에게 요청하고 결과를 기다릴 때 까지 스레드를 점유하면, 스레드가 계속해서 사용되고 있는 상황이 유지된다. 따라서, 다수의 유저에게 응답해줄 수 없다. 이러한 문제로 인하여 적은 양의 스레드와 최소한의 하드웨어 자원으로 동시성을 핸들링하기 위해 만들어졌다. 단일 스레드에서 Blocking I/O 와 Non-Blocking I/O 를 비교하면 아래와 같습니다. 1.2. WebFlux 특징 WebFlux 는 이를 리액티브 프로그래밍 방식을 사용하여 논블로킹과 고정된 스레드로 모든 요청을 처리하여 기존의 문제를 해결한다. thread:many_request(1:N), async + nonblocking 방식 Spring Framwork5에서 새롭게 추가된 모듈이며 reactive 스타일의 어플리케이션 개발을 도와준다 reactive 란? reactive란 반응형 프로그래밍으로 변화에 반응하게 만들어진 프로그래밍 모델 반응형 프로그래밍은 데이터 스트림을 처리하며 이 데이터 스트림이 변경될 때마다 반응 기존에 사용하던 명령형 프로그래밍의 경우는 컴퓨터가 수행해야 하는 일을 순서대로 처리 WebFlux 는 반응형 프로그래밍(Reactive Programming) 방식을 통해 Event-Driven(이벤트 기반)의 비동기식 애플리케이션을 구축 reactive-stack web framework이며 non-blocking에 Reactive stream 지원 반응형 스트림(Reactive Stream)에서 Publisher-Subscriber 패턴을 사용 Publisher는 데이터를 생성하고 Subscriber는 이를 처리 이벤트 스트림에 있는 데이터를 Subscriber가 비동기적으로 가져옴 tomcat이 아닌 netty 같은 async, non-blocking 서버 사용 webflux Non-Blocking Request을 수행 중에 결과가 반환되지 않더라도 다른 작업 수행 가능 동기 프로그래밍과 비교하여 디버깅이 어려움 비동기 소스코드 안에 동기 코드가 있으면, 비동기로 동작하지 않을 수 있어 주의 필요 서비스간 호출이 많은 마이크로서비스 아키텍처에 적합 reference https://heeyeah.github.io/spring/2020-02-29-web-flux/ https://adjh54.tistory.com/232 https://devmoony.tistory.com/174 https://techblog.woowahan.com/2667/]]></summary></entry><entry><title type="html">[AWS] SNS, SQS 란? 비동기 메시지 큐 개념정리 및 차이점 비교</title><link href="https://melonicedlatte.com/2023/11/20/141900.html" rel="alternate" type="text/html" title="[AWS] SNS, SQS 란? 비동기 메시지 큐 개념정리 및 차이점 비교" /><published>2023-11-20T00:00:00+09:00</published><updated>2023-11-20T00:00:00+09:00</updated><id>https://melonicedlatte.com/2023/11/20/141900</id><content type="html" xml:base="https://melonicedlatte.com/2023/11/20/141900.html"><![CDATA[<h2 id="0-들어가기-전">0. 들어가기 전</h2>

<ul>
  <li>AWS SNS, SQS 를 사용하면서 궁금한 점을 정리하게 되었습니다.
    <ul>
      <li>특히, <a href="https://seohyun0120.tistory.com/entry/AWS-SNS-vs-SQS-%EC%B0%A8%EC%9D%B4%EC%A0%90">seohyun0120 님의 블로그 _ AWS SNS vs SQS 차이점</a>의 많은 도움을 받았습니다.</li>
    </ul>
  </li>
  <li>서비스가 커질수록 서버 한대로는 처리가 힘들어진다. 여러 서버에서 기능을 처리하면서 서버들끼리 주고 받는 메세지를 <strong>잃어버리지 않고 정확하게 처리</strong>하는 것이 중요해졌다.
    <ul>
      <li>이러한 니즈에 따라 중간에 <code class="language-plaintext highlighter-rouge">큐</code> 를 두고 서비스를 개발하게 되었다.</li>
      <li>이러한 <code class="language-plaintext highlighter-rouge">큐</code> 서비스는 다중화 구성을 기본으로 장애 걱정 없이 믿을 만한 시스템으로 구축</li>
      <li>시스템 일부에 장애가 발생하더라도, 시스템 전체로 보자면 정상 작동하도록 믿을 수 있는 높은 신뢰도를 바탕으로 운영</li>
    </ul>
  </li>
  <li><strong>서비스끼리의 의존성을 낮추고 싶다</strong>.
    <ul>
      <li>A 서비스에서 B 서비스를 직접 호출하게되면
        <ul>
          <li>오류가 발생하여 제대로 로직이 수행되지 않을 수 있다.</li>
          <li>A 서비스 코드 상에 B 서비스에 대한 코드가 입력되어, A 와 B의 의존성이 높아진다.</li>
        </ul>
      </li>
      <li>이러한 문제를 중간에 계층을 하나 두어, 서비스 간의 의존성을 낮춘다.</li>
    </ul>
  </li>
  <li><strong>요청을 비동기적으로 처리</strong>하고 싶을 수 있다.
    <ul>
      <li>모든 요청을 동기적으로 처리하면 리소스가 많이 사용될 수 있다.</li>
    </ul>
  </li>
  <li><strong>여러 서비스에서 동일한 요청에 대하여 처리</strong>하고 싶을 수 있다.
    <ul>
      <li>ex. 유저가 물품을 구매한다고 가정해보자.
        <ul>
          <li>먼저, 구매 서비스에서 결제 처리 진행을 할 것이다.</li>
          <li>결제가 완료되면 아래와 같은 다양한 것들을 하고 싶을 수 있다.
            <ul>
              <li>알림 서비스 : email, 메시지 전송</li>
              <li>쿠폰 서비스 : 이벤트 쿠폰 발행</li>
              <li>데이터 서비스 : 실시간 분석을 위한 Data warehouse 에 데이터 전송</li>
            </ul>
          </li>
          <li>구매 서비스에서 위 서비스들을 모두 알고 있으면 의존성이 높아진다. 또한, 새로운 서비스를 추가하고 싶으면 구매 서비스의 코드를 고쳐야한다. 구매 서비스와 다른 서비스들간의 의존성이 높아진 것이다.</li>
          <li>큐를 두게 되면 서비스가 하나 추가되거나 서비스의 구현이 변경되더라도 구매 서비스는 변경하지 않아도 된다.</li>
        </ul>
      </li>
      <li><strong>AWS 에서는 SNS 을 사용하여 구매 서비스가 이벤트를 전송하면, SNS 을 구독하고 있는 서비스들이 해당 요청을 처리한다. 이 때, 요청이 손실되지 않게 SQS 를 사용하는 것으로 보인다.</strong></li>
    </ul>
  </li>
  <li>Amazon SQS와 Amazon SNS를 함께 사용하여 데이터를 생성하는 경우가 많다.
    <ul>
      <li><a href="https://aws.amazon.com/ko/getting-started/hands-on/send-fanout-event-notifications/">Send Fanout Event Notifications / with Amazon Simple Queue Service (SQS) and Amazon Simple Notification Service (SNS)</a>
<img src="/assets/images/2022/2023-11-20-14-54-52.png" alt="image" class="rounded img_center border_2em" /></li>
    </ul>
  </li>
</ul>

<h2 id="1-aws-sns-란">1. AWS SNS 란?</h2>

<ul>
  <li>다수의 구독자가 메시지 소비
    <ul>
      <li>같은 메시지를 여러 소비자에게 발행</li>
      <li>하나의 이벤트가 다수의 구독자에게 사용되어야 될 때 사용</li>
    </ul>
  </li>
  <li>메세지를 받는 사용자가 없으면 몇 번 시도하다가 삭제된다.
    <ul>
      <li>위의 이미지에서 Lambda 에 이상이 있어 SNS 에서 데이터를 받아오던 중 오류가 발생하면, Lambda 는 이후 다시 이벤트를 처리하지 않는다.</li>
    </ul>
  </li>
  <li><strong>게시자(==생산자)에서 여러 구독자 엔드포인트(==소비자) 로 메시지를 전송</strong>하는 게시-구독 서비스. 게시자는 논리적 액세스 지점 및 커뮤니케이션 채널인 주제에 메시지를 전송하여 구독자와 비동기식으로 통신합니다.</li>
  <li>Amazon SNS는 메시지 라우터 역할을 하며 구독자에게 메시지를 실시간으로 전송
    <ul>
      <li>메시지 게시 시점에 구독자가 없는 경우, 메시지는 나중에 검색할 수 있도록 저장하지 않음.</li>
    </ul>
  </li>
</ul>

<h2 id="2-aws-sqs-란">2. AWS SQS 란?</h2>

<ul>
  <li>일반적으로 단일 구독자가 메시지 소비
    <ul>
      <li>들어온 메시지에 대하여 하나의 서비스가 최소한 한 번 실행해야 할 때 사용</li>
    </ul>
  </li>
  <li>메세지는 일정 기간동안 유지된다(최대 14일)</li>
  <li>위의 이미지에서 Lambda 는 문제가 발생하면 다시 메시지를 처리하지 않았다.
    <ul>
      <li>하지만 SQS(이미지의 Transaction Analytics &amp; Fraud Detection Queue) 가 연결되어 있다면, 완료되지 않은 메시지가 남아 있기 때문에 다시 try 할 수 있다.</li>
    </ul>
  </li>
  <li>두 가지 큐 종류 존재
    <ul>
      <li>표준대기열
        <ul>
          <li>순서 보장하지 않음</li>
          <li>최소 한번 (중복 수신 가능)
            <ul>
              <li>At least once – 최소 한 번 이상 메시지 전송을 약속</li>
            </ul>
          </li>
          <li>처리량 제한 없음 (이론상 무제한)</li>
        </ul>
      </li>
      <li>FIFO 대기열
        <ul>
          <li>순서 보장</li>
          <li>정확히 한번
            <ul>
              <li>Exactly once – 정확히 딱 한 번 메시지 전송되는 것을 약속 (중복 메시지 제거)</li>
            </ul>
          </li>
          <li>시스템 당 최대 초당 300건의 API 처리 가능</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>Consumer 가 메시지 소비 후, SQS 에 메시지를 지우라고 요청</li>
</ul>

<h2 id="3-aws-sns-vs-sqs-개념-정리-및-차이점-비교">3. AWS SNS vs SQS 개념 정리 및 차이점 비교</h2>

<h3 id="31-aws의-sns-sqs-mq-서비스-비교-자료">3.1. AWS의 SNS, SQS, MQ 서비스 비교 자료</h3>

<table>
  <thead>
    <tr>
      <th>리소스 유형</th>
      <th>Amazon SNS</th>
      <th>Amazon SQS</th>
      <th>Amazon MQ</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>동기식</strong></td>
      <td>아니요</td>
      <td>아니요</td>
      <td>예</td>
    </tr>
    <tr>
      <td><strong>비동기식</strong></td>
      <td>예</td>
      <td>예</td>
      <td>예</td>
    </tr>
    <tr>
      <td><strong>대기열</strong></td>
      <td>아니요</td>
      <td>예</td>
      <td>예</td>
    </tr>
    <tr>
      <td><strong>게시자-구독자 메시징</strong></td>
      <td>예</td>
      <td>아니요</td>
      <td>예</td>
    </tr>
    <tr>
      <td><strong>메시지 브로커</strong></td>
      <td>아니요</td>
      <td>아니요</td>
      <td>예</td>
    </tr>
  </tbody>
</table>

<h3 id="32-차이점-비교">3.2. 차이점 비교</h3>

<table>
  <thead>
    <tr>
      <th><strong>특징</strong></th>
      <th><strong>SNS</strong></th>
      <th><strong>SQS</strong></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>이름</strong></td>
      <td>Simple Notification Service</td>
      <td>Simple Queue Service</td>
    </tr>
    <tr>
      <td><strong>메시지를 발행하는 곳</strong></td>
      <td>Topic(Pub/Sub)</td>
      <td>Queue</td>
    </tr>
    <tr>
      <td><strong>메시지 소비자 특징</strong></td>
      <td>게시자 (생산자라고도 함) 에서 <strong>여러 구독자</strong> 엔드포인트 (소비자라고도 함) 로 메시지를 전송하는 게시-구독 서비스</td>
      <td>대기열에 있는 메시지는 일반적으로 <strong>단일 구독자</strong>가 처리</td>
    </tr>
    <tr>
      <td><strong>전송 방식</strong></td>
      <td>Push: 사용자에게 메세지 전송</td>
      <td>Pull: 사용자가 메세지를 가져온다</td>
    </tr>
    <tr>
      <td> </td>
      <td>Fanout: 같은 메세지를 여러 방향으로 발행</td>
      <td>Decouple: 여러 서비스로 분리하여 병렬식 비동기 처리</td>
    </tr>
    <tr>
      <td> </td>
      <td>메세지를 받는 사용자가 없으면 몇 번 시도하다가 삭제된다. 전송 후 보관 없이 메시지가 사라지는 방식</td>
      <td>메세지는 일정 기간동안 유지된다. (최대 14일)</td>
    </tr>
    <tr>
      <td> </td>
      <td>Publisher(게시자)가 Subscriber(구독자)에게 메세지를 전송하는 관리형 서비스</td>
      <td>마이크로서비스, 분산 시스템 및 서버리스 애플리케이션을 쉽게 분리하고 확장할 수 있도록 지원하는 완전관리형 메세지 대기열 서비스</td>
    </tr>
    <tr>
      <td> </td>
      <td>Publisher는 Topic(주제)에 메세지를 발행한다.Topic은 수많은 Subscribers(구독자들)에게 전달될 수 있다.(fan out)이때 전달 방식은 다양하다.(Lambda, SQS, Email …)</td>
      <td>시스템은 Queue로부터 새로운 이벤트를 실시할 수 있다.Queue에 있는 메세지들은 한 명의 consumer(고객) 또는 하나의 서비스에서 실행된다.</td>
    </tr>
    <tr>
      <td> </td>
      <td>다른 시스템들이 이벤트에 신경쓰는가? Topic에 메세지를 publish(발행)하고 싶어하고, 사람들에게 발행되었다고 알리고 싶을 때</td>
      <td>이 시스템이 이벤트에 신경쓰는가? 내가 이벤트의 수신자일 때</td>
    </tr>
  </tbody>
</table>

<hr />

<p><strong><em>reference</em></strong></p>

<ul>
  <li>https://docs.aws.amazon.com/ko_kr/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-difference-from-amazon-mq-sns.html</li>
  <li>https://seohyun0120.tistory.com/entry/AWS-SNS-vs-SQS-%EC%B0%A8%EC%9D%B4%EC%A0%90</li>
  <li>https://youtu.be/mXk0MNjlO7A?feature=shared</li>
  <li>https://note.hatemogi.com/amazon-sqs.html</li>
</ul>]]></content><author><name>melonicedlatte</name></author><category term="Aws" /><summary type="html"><![CDATA[0. 들어가기 전 AWS SNS, SQS 를 사용하면서 궁금한 점을 정리하게 되었습니다. 특히, seohyun0120 님의 블로그 _ AWS SNS vs SQS 차이점의 많은 도움을 받았습니다. 서비스가 커질수록 서버 한대로는 처리가 힘들어진다. 여러 서버에서 기능을 처리하면서 서버들끼리 주고 받는 메세지를 잃어버리지 않고 정확하게 처리하는 것이 중요해졌다. 이러한 니즈에 따라 중간에 큐 를 두고 서비스를 개발하게 되었다. 이러한 큐 서비스는 다중화 구성을 기본으로 장애 걱정 없이 믿을 만한 시스템으로 구축 시스템 일부에 장애가 발생하더라도, 시스템 전체로 보자면 정상 작동하도록 믿을 수 있는 높은 신뢰도를 바탕으로 운영 서비스끼리의 의존성을 낮추고 싶다. A 서비스에서 B 서비스를 직접 호출하게되면 오류가 발생하여 제대로 로직이 수행되지 않을 수 있다. A 서비스 코드 상에 B 서비스에 대한 코드가 입력되어, A 와 B의 의존성이 높아진다. 이러한 문제를 중간에 계층을 하나 두어, 서비스 간의 의존성을 낮춘다. 요청을 비동기적으로 처리하고 싶을 수 있다. 모든 요청을 동기적으로 처리하면 리소스가 많이 사용될 수 있다. 여러 서비스에서 동일한 요청에 대하여 처리하고 싶을 수 있다. ex. 유저가 물품을 구매한다고 가정해보자. 먼저, 구매 서비스에서 결제 처리 진행을 할 것이다. 결제가 완료되면 아래와 같은 다양한 것들을 하고 싶을 수 있다. 알림 서비스 : email, 메시지 전송 쿠폰 서비스 : 이벤트 쿠폰 발행 데이터 서비스 : 실시간 분석을 위한 Data warehouse 에 데이터 전송 구매 서비스에서 위 서비스들을 모두 알고 있으면 의존성이 높아진다. 또한, 새로운 서비스를 추가하고 싶으면 구매 서비스의 코드를 고쳐야한다. 구매 서비스와 다른 서비스들간의 의존성이 높아진 것이다. 큐를 두게 되면 서비스가 하나 추가되거나 서비스의 구현이 변경되더라도 구매 서비스는 변경하지 않아도 된다. AWS 에서는 SNS 을 사용하여 구매 서비스가 이벤트를 전송하면, SNS 을 구독하고 있는 서비스들이 해당 요청을 처리한다. 이 때, 요청이 손실되지 않게 SQS 를 사용하는 것으로 보인다. Amazon SQS와 Amazon SNS를 함께 사용하여 데이터를 생성하는 경우가 많다. Send Fanout Event Notifications / with Amazon Simple Queue Service (SQS) and Amazon Simple Notification Service (SNS) 1. AWS SNS 란? 다수의 구독자가 메시지 소비 같은 메시지를 여러 소비자에게 발행 하나의 이벤트가 다수의 구독자에게 사용되어야 될 때 사용 메세지를 받는 사용자가 없으면 몇 번 시도하다가 삭제된다. 위의 이미지에서 Lambda 에 이상이 있어 SNS 에서 데이터를 받아오던 중 오류가 발생하면, Lambda 는 이후 다시 이벤트를 처리하지 않는다. 게시자(==생산자)에서 여러 구독자 엔드포인트(==소비자) 로 메시지를 전송하는 게시-구독 서비스. 게시자는 논리적 액세스 지점 및 커뮤니케이션 채널인 주제에 메시지를 전송하여 구독자와 비동기식으로 통신합니다. Amazon SNS는 메시지 라우터 역할을 하며 구독자에게 메시지를 실시간으로 전송 메시지 게시 시점에 구독자가 없는 경우, 메시지는 나중에 검색할 수 있도록 저장하지 않음. 2. AWS SQS 란? 일반적으로 단일 구독자가 메시지 소비 들어온 메시지에 대하여 하나의 서비스가 최소한 한 번 실행해야 할 때 사용 메세지는 일정 기간동안 유지된다(최대 14일) 위의 이미지에서 Lambda 는 문제가 발생하면 다시 메시지를 처리하지 않았다. 하지만 SQS(이미지의 Transaction Analytics &amp; Fraud Detection Queue) 가 연결되어 있다면, 완료되지 않은 메시지가 남아 있기 때문에 다시 try 할 수 있다. 두 가지 큐 종류 존재 표준대기열 순서 보장하지 않음 최소 한번 (중복 수신 가능) At least once – 최소 한 번 이상 메시지 전송을 약속 처리량 제한 없음 (이론상 무제한) FIFO 대기열 순서 보장 정확히 한번 Exactly once – 정확히 딱 한 번 메시지 전송되는 것을 약속 (중복 메시지 제거) 시스템 당 최대 초당 300건의 API 처리 가능 Consumer 가 메시지 소비 후, SQS 에 메시지를 지우라고 요청 3. AWS SNS vs SQS 개념 정리 및 차이점 비교 3.1. AWS의 SNS, SQS, MQ 서비스 비교 자료 리소스 유형 Amazon SNS Amazon SQS Amazon MQ 동기식 아니요 아니요 예 비동기식 예 예 예 대기열 아니요 예 예 게시자-구독자 메시징 예 아니요 예 메시지 브로커 아니요 아니요 예 3.2. 차이점 비교 특징 SNS SQS 이름 Simple Notification Service Simple Queue Service 메시지를 발행하는 곳 Topic(Pub/Sub) Queue 메시지 소비자 특징 게시자 (생산자라고도 함) 에서 여러 구독자 엔드포인트 (소비자라고도 함) 로 메시지를 전송하는 게시-구독 서비스 대기열에 있는 메시지는 일반적으로 단일 구독자가 처리 전송 방식 Push: 사용자에게 메세지 전송 Pull: 사용자가 메세지를 가져온다   Fanout: 같은 메세지를 여러 방향으로 발행 Decouple: 여러 서비스로 분리하여 병렬식 비동기 처리   메세지를 받는 사용자가 없으면 몇 번 시도하다가 삭제된다. 전송 후 보관 없이 메시지가 사라지는 방식 메세지는 일정 기간동안 유지된다. (최대 14일)   Publisher(게시자)가 Subscriber(구독자)에게 메세지를 전송하는 관리형 서비스 마이크로서비스, 분산 시스템 및 서버리스 애플리케이션을 쉽게 분리하고 확장할 수 있도록 지원하는 완전관리형 메세지 대기열 서비스   Publisher는 Topic(주제)에 메세지를 발행한다.Topic은 수많은 Subscribers(구독자들)에게 전달될 수 있다.(fan out)이때 전달 방식은 다양하다.(Lambda, SQS, Email …) 시스템은 Queue로부터 새로운 이벤트를 실시할 수 있다.Queue에 있는 메세지들은 한 명의 consumer(고객) 또는 하나의 서비스에서 실행된다.   다른 시스템들이 이벤트에 신경쓰는가? Topic에 메세지를 publish(발행)하고 싶어하고, 사람들에게 발행되었다고 알리고 싶을 때 이 시스템이 이벤트에 신경쓰는가? 내가 이벤트의 수신자일 때 reference https://docs.aws.amazon.com/ko_kr/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-difference-from-amazon-mq-sns.html https://seohyun0120.tistory.com/entry/AWS-SNS-vs-SQS-%EC%B0%A8%EC%9D%B4%EC%A0%90 https://youtu.be/mXk0MNjlO7A?feature=shared https://note.hatemogi.com/amazon-sqs.html]]></summary></entry><entry><title type="html">[leetcode] 100. Same Tree _ Algorithm Problem Solve for python</title><link href="https://melonicedlatte.com/2023/11/19/141400.html" rel="alternate" type="text/html" title="[leetcode] 100. Same Tree _ Algorithm Problem Solve for python" /><published>2023-11-19T00:00:00+09:00</published><updated>2023-11-19T00:00:00+09:00</updated><id>https://melonicedlatte.com/2023/11/19/141400</id><content type="html" xml:base="https://melonicedlatte.com/2023/11/19/141400.html"><![CDATA[<h2 id="1-problem">1. Problem</h2>

<p><a href="https://leetcode.com/problems/same-tree/">100. Same Tree</a></p>

<p>Given the roots of two binary trees p and q, write a function to check if they are the same or not.</p>

<p>Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.</p>

<p><strong>Example 1:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Input: p = [1,2,3], q = [1,2,3]
Output: true
</code></pre></div></div>

<p><strong>Example 2:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Input: p = [1,2], q = [1,null,2]
Output: false
</code></pre></div></div>

<p><strong>Example 3:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Input: p = [1,2,1], q = [1,1,2]
Output: false
</code></pre></div></div>

<p><strong>Constraints:</strong></p>

<ul>
  <li>The number of nodes in both trees is in the range [0, 100].</li>
  <li>-10^4 &lt;= Node.val &lt;= 10^4</li>
</ul>

<h2 id="2-solution">2. Solution</h2>

<p>I solved this problem like this.</p>

<ul>
  <li>Make two list ans1, ans2.</li>
  <li>Using dfs, put node on list.
    <ul>
      <li>Check now node. Append node value on list and return if node is None value.</li>
      <li>Check left, right node. If node has child, go to dfs. If node don’t have child, append node value.</li>
    </ul>
  </li>
  <li>All node are inserted, check two list have same value.</li>
</ul>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Solution</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">isSameTree</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">p</span><span class="p">:</span> <span class="n">Optional</span><span class="p">[</span><span class="n">TreeNode</span><span class="p">],</span> <span class="n">q</span><span class="p">:</span> <span class="n">Optional</span><span class="p">[</span><span class="n">TreeNode</span><span class="p">])</span> <span class="o">-&gt;</span> <span class="nb">bool</span><span class="p">:</span>
        <span class="k">def</span> <span class="nf">dfs</span><span class="p">(</span><span class="n">node</span><span class="p">,</span> <span class="n">ans</span><span class="p">):</span>
            <span class="k">if</span> <span class="ow">not</span> <span class="n">node</span><span class="p">:</span>
                <span class="n">ans</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">node</span><span class="p">)</span>
                <span class="k">return</span>
            <span class="n">ans</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">node</span><span class="p">.</span><span class="n">val</span><span class="p">)</span>
            <span class="n">dfs</span><span class="p">(</span><span class="n">node</span><span class="p">.</span><span class="n">left</span><span class="p">,</span> <span class="n">ans</span><span class="p">)</span> <span class="k">if</span> <span class="n">node</span><span class="p">.</span><span class="n">left</span> <span class="k">else</span> <span class="n">ans</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">node</span><span class="p">.</span><span class="n">left</span><span class="p">)</span>
            <span class="n">dfs</span><span class="p">(</span><span class="n">node</span><span class="p">.</span><span class="n">right</span><span class="p">,</span> <span class="n">ans</span><span class="p">)</span> <span class="k">if</span> <span class="n">node</span><span class="p">.</span><span class="n">right</span> <span class="k">else</span> <span class="n">ans</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">node</span><span class="p">.</span><span class="n">right</span><span class="p">)</span>
            
        <span class="n">ans1</span><span class="p">,</span> <span class="n">ans2</span> <span class="o">=</span> <span class="p">[],</span> <span class="p">[]</span>
        <span class="n">dfs</span><span class="p">(</span><span class="n">p</span><span class="p">,</span> <span class="n">ans1</span><span class="p">),</span> <span class="n">dfs</span><span class="p">(</span><span class="n">q</span><span class="p">,</span> <span class="n">ans2</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">ans1</span> <span class="o">==</span> <span class="n">ans2</span>
</code></pre></div></div>]]></content><author><name>melonicedlatte</name></author><category term="Algorithm" /><summary type="html"><![CDATA[1. Problem 100. Same Tree Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. Example 1: Input: p = [1,2,3], q = [1,2,3] Output: true Example 2: Input: p = [1,2], q = [1,null,2] Output: false Example 3: Input: p = [1,2,1], q = [1,1,2] Output: false Constraints: The number of nodes in both trees is in the range [0, 100]. -10^4 &lt;= Node.val &lt;= 10^4 2. Solution I solved this problem like this. Make two list ans1, ans2. Using dfs, put node on list. Check now node. Append node value on list and return if node is None value. Check left, right node. If node has child, go to dfs. If node don’t have child, append node value. All node are inserted, check two list have same value. class Solution: def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -&gt; bool: def dfs(node, ans): if not node: ans.append(node) return ans.append(node.val) dfs(node.left, ans) if node.left else ans.append(node.left) dfs(node.right, ans) if node.right else ans.append(node.right) ans1, ans2 = [], [] dfs(p, ans1), dfs(q, ans2) return ans1 == ans2]]></summary></entry><entry><title type="html">[leetcode] 9. Palindrome Number _ Algorithm Problem Solve for python</title><link href="https://melonicedlatte.com/2023/11/19/143400.html" rel="alternate" type="text/html" title="[leetcode] 9. Palindrome Number _ Algorithm Problem Solve for python" /><published>2023-11-19T00:00:00+09:00</published><updated>2023-11-19T00:00:00+09:00</updated><id>https://melonicedlatte.com/2023/11/19/143400</id><content type="html" xml:base="https://melonicedlatte.com/2023/11/19/143400.html"><![CDATA[<h2 id="1-problem">1. Problem</h2>

<p><a href="https://leetcode.com/problems/palindrome-number/">9. Palindrome Number</a></p>

<p>Given an integer x, return true if x is a palindrome, and false otherwise.</p>

<p><strong>Example 1:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
</code></pre></div></div>

<p><strong>Example 2:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
</code></pre></div></div>

<p><strong>Example 3:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
</code></pre></div></div>

<p><strong>Constraints:</strong></p>

<ul>
  <li>-2^31 &lt;= x &lt;= 2^31 - 1</li>
</ul>

<h2 id="2-solution">2. Solution</h2>

<p>I solved this problem like this.</p>

<ul>
  <li>It is so easy!</li>
  <li>You change x to str.</li>
  <li>confirm str(x) and str(x)[::-1] are equal.</li>
</ul>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Solution</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">isPalindrome</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">:</span> <span class="nb">int</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">bool</span><span class="p">:</span>
        <span class="k">return</span> <span class="nb">str</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="o">==</span> <span class="nb">str</span><span class="p">(</span><span class="n">x</span><span class="p">)[::</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
</code></pre></div></div>]]></content><author><name>melonicedlatte</name></author><category term="Algorithm" /><summary type="html"><![CDATA[1. Problem 9. Palindrome Number Given an integer x, return true if x is a palindrome, and false otherwise. Example 1: Input: x = 121 Output: true Explanation: 121 reads as 121 from left to right and from right to left. Example 2: Input: x = -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Example 3: Input: x = 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. Constraints: -2^31 &lt;= x &lt;= 2^31 - 1 2. Solution I solved this problem like this. It is so easy! You change x to str. confirm str(x) and str(x)[::-1] are equal. class Solution: def isPalindrome(self, x: int) -&gt; bool: return str(x) == str(x)[::-1]]]></summary></entry><entry><title type="html">[leetcode] 190. Reverse Bits _ Algorithm Problem Solve for python</title><link href="https://melonicedlatte.com/2023/11/19/150400.html" rel="alternate" type="text/html" title="[leetcode] 190. Reverse Bits _ Algorithm Problem Solve for python" /><published>2023-11-19T00:00:00+09:00</published><updated>2023-11-19T00:00:00+09:00</updated><id>https://melonicedlatte.com/2023/11/19/150400</id><content type="html" xml:base="https://melonicedlatte.com/2023/11/19/150400.html"><![CDATA[<h2 id="1-problem">1. Problem</h2>

<p><a href="https://leetcode.com/problems/reverse-bits/">190. Reverse Bits</a></p>

<p>Reverse bits of a given 32 bits unsigned integer.</p>

<p><strong>Note:</strong></p>

<ul>
  <li>Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer’s internal binary representation is the same, whether it is signed or unsigned.</li>
  <li>In Java, the compiler represents the signed integers using 2’s complement notation. Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825.</li>
</ul>

<p><strong>Example 1:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Input: n = 00000010100101000001111010011100
Output:    964176192 (00111001011110000010100101000000)
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.
</code></pre></div></div>

<p><strong>Example 2:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Input: n = 11111111111111111111111111111101
Output:   3221225471 (10111111111111111111111111111111)
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.
</code></pre></div></div>

<p><strong>Constraints:</strong></p>

<ul>
  <li>The input must be a binary string of length 32</li>
</ul>

<h2 id="2-solution">2. Solution</h2>

<p>I solved this problem like this.</p>

<ul>
  <li>It is so easy!</li>
  <li>I can use ‘{0:032b}’.format(n). It makes n to binary num.</li>
  <li>And i use int(binary_string, 2), i can get int.</li>
</ul>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Solution</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">reverseBits</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">n</span><span class="p">:</span> <span class="nb">int</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">int</span><span class="p">:</span>
        <span class="n">bi_num</span> <span class="o">=</span> <span class="s">'{0:032b}'</span><span class="p">.</span><span class="nb">format</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
        <span class="n">ans</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">bi_num</span><span class="p">[::</span><span class="o">-</span><span class="mi">1</span><span class="p">],</span> <span class="mi">2</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">ans</span>
</code></pre></div></div>]]></content><author><name>melonicedlatte</name></author><category term="Algorithm" /><summary type="html"><![CDATA[1. Problem 190. Reverse Bits Reverse bits of a given 32 bits unsigned integer. Note: Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer’s internal binary representation is the same, whether it is signed or unsigned. In Java, the compiler represents the signed integers using 2’s complement notation. Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825. Example 1: Input: n = 00000010100101000001111010011100 Output: 964176192 (00111001011110000010100101000000) Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000. Example 2: Input: n = 11111111111111111111111111111101 Output: 3221225471 (10111111111111111111111111111111) Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111. Constraints: The input must be a binary string of length 32 2. Solution I solved this problem like this. It is so easy! I can use ‘{0:032b}’.format(n). It makes n to binary num. And i use int(binary_string, 2), i can get int. class Solution: def reverseBits(self, n: int) -&gt; int: bi_num = '{0:032b}'.format(n) ans = int(bi_num[::-1], 2) return ans]]></summary></entry><entry><title type="html">[leetcode] 137. Single Number II _ Algorithm Problem Solve for python</title><link href="https://melonicedlatte.com/2023/11/19/151200.html" rel="alternate" type="text/html" title="[leetcode] 137. Single Number II _ Algorithm Problem Solve for python" /><published>2023-11-19T00:00:00+09:00</published><updated>2023-11-19T00:00:00+09:00</updated><id>https://melonicedlatte.com/2023/11/19/151200</id><content type="html" xml:base="https://melonicedlatte.com/2023/11/19/151200.html"><![CDATA[<h2 id="1-problem">1. Problem</h2>

<p><a href="https://leetcode.com/problems/single-number-ii/">137. Single Number II</a></p>

<p>Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it.</p>

<p>You must implement a solution with a linear runtime complexity and use only constant extra space.</p>

<p><strong>Example 1:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Input: nums = [2,2,3,2]
Output: 3
</code></pre></div></div>

<p><strong>Example 2:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Input: nums = [0,1,0,1,0,1,99]
Output: 99
</code></pre></div></div>

<p><strong>Constraints:</strong></p>

<ul>
  <li>1 &lt;= nums.length &lt;= 3 * 104</li>
  <li>-2^31 &lt;= nums[i] &lt;= 2^31 - 1</li>
  <li>Each element in nums appears exactly three times except for one element which appears once.</li>
</ul>

<h2 id="2-solution">2. Solution</h2>

<p>I solved this problem like this.</p>

<ul>
  <li>Using dictionary, count all numbers.</li>
  <li>Find dictionary value is 1 and return that key.</li>
</ul>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Solution</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">singleNumber</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">nums</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="nb">int</span><span class="p">])</span> <span class="o">-&gt;</span> <span class="nb">int</span><span class="p">:</span>
        <span class="n">dic</span> <span class="o">=</span> <span class="p">{}</span>
        <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">nums</span><span class="p">:</span>
            <span class="k">if</span> <span class="n">x</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">dic</span><span class="p">:</span>
                <span class="n">dic</span><span class="p">[</span><span class="n">x</span><span class="p">]</span> <span class="o">=</span> <span class="mi">0</span>
            <span class="n">dic</span><span class="p">[</span><span class="n">x</span><span class="p">]</span> <span class="o">+=</span> <span class="mi">1</span>
        
        <span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">dic</span><span class="p">:</span>
            <span class="k">if</span> <span class="n">dic</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
                <span class="k">return</span> <span class="n">key</span>

        <span class="k">return</span> <span class="o">-</span><span class="mi">1</span>
</code></pre></div></div>]]></content><author><name>melonicedlatte</name></author><category term="Algorithm" /><summary type="html"><![CDATA[1. Problem 137. Single Number II Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it. You must implement a solution with a linear runtime complexity and use only constant extra space. Example 1: Input: nums = [2,2,3,2] Output: 3 Example 2: Input: nums = [0,1,0,1,0,1,99] Output: 99 Constraints: 1 &lt;= nums.length &lt;= 3 * 104 -2^31 &lt;= nums[i] &lt;= 2^31 - 1 Each element in nums appears exactly three times except for one element which appears once. 2. Solution I solved this problem like this. Using dictionary, count all numbers. Find dictionary value is 1 and return that key. class Solution: def singleNumber(self, nums: List[int]) -&gt; int: dic = {} for x in nums: if x not in dic: dic[x] = 0 dic[x] += 1 for key in dic: if dic[key] == 1: return key return -1]]></summary></entry><entry><title type="html">[leetcode] 207. Course Schedule _ Algorithm Problem Solve for python</title><link href="https://melonicedlatte.com/2023/11/19/171500.html" rel="alternate" type="text/html" title="[leetcode] 207. Course Schedule _ Algorithm Problem Solve for python" /><published>2023-11-19T00:00:00+09:00</published><updated>2023-11-19T00:00:00+09:00</updated><id>https://melonicedlatte.com/2023/11/19/171500</id><content type="html" xml:base="https://melonicedlatte.com/2023/11/19/171500.html"><![CDATA[<h2 id="1-problem">1. Problem</h2>

<p><a href="https://leetcode.com/problems/course-schedule/">207. Course Schedule</a></p>

<p>There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.</p>

<ul>
  <li>For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
Return true if you can finish all courses. Otherwise, return false.</li>
</ul>

<p><strong>Example 1:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take. 
To take course 1 you should have finished course 0. So it is possible.
</code></pre></div></div>

<p><strong>Example 2:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take. 
To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
</code></pre></div></div>

<p><strong>Constraints:</strong></p>

<ul>
  <li>1 &lt;= numCourses &lt;= 2000</li>
  <li>0 &lt;= prerequisites.length &lt;= 5000</li>
  <li>prerequisites[i].length == 2</li>
  <li>0 &lt;= ai, bi &lt; numCourses</li>
  <li>All the pairs prerequisites[i] are unique.</li>
</ul>

<h2 id="2-solution">2. Solution</h2>

<p>I solved this problem like this.</p>

<ul>
  <li>This problem is related to topological sorting.</li>
  <li>Check nodes adj node. I used dictionary.</li>
  <li>Check nodes indegree. I used list.</li>
  <li>Check nodes that each node’s indegree is 0. I put all 0 indegree nodes on deque.</li>
  <li>While deque is empty, pop node and renew is_visited.</li>
  <li>Check that node’s adj and decrease the indegree value by 1.</li>
  <li>If sum(is_visited) == numCourses means that i can visit all nodes, that means there is no cycle.</li>
</ul>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Solution</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">canFinish</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">numCourses</span><span class="p">:</span> <span class="nb">int</span><span class="p">,</span> <span class="n">prerequisites</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="n">List</span><span class="p">[</span><span class="nb">int</span><span class="p">]])</span> <span class="o">-&gt;</span> <span class="nb">bool</span><span class="p">:</span>
        <span class="n">adj</span> <span class="o">=</span> <span class="p">{}</span>
        <span class="n">indegree</span> <span class="o">=</span> <span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">*</span> <span class="n">numCourses</span>
        <span class="n">is_visited</span> <span class="o">=</span> <span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">*</span> <span class="n">numCourses</span>
        <span class="k">for</span> <span class="n">second</span><span class="p">,</span> <span class="n">first</span> <span class="ow">in</span> <span class="n">prerequisites</span><span class="p">:</span>
            <span class="n">indegree</span><span class="p">[</span><span class="n">second</span><span class="p">]</span> <span class="o">+=</span> <span class="mi">1</span>
            <span class="k">if</span> <span class="n">first</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">adj</span><span class="p">:</span>
                <span class="n">adj</span><span class="p">[</span><span class="n">first</span><span class="p">]</span> <span class="o">=</span> <span class="p">[]</span>
            <span class="n">adj</span><span class="p">[</span><span class="n">first</span><span class="p">].</span><span class="n">append</span><span class="p">(</span><span class="n">second</span><span class="p">)</span>

        <span class="n">node_list</span> <span class="o">=</span> <span class="p">[</span><span class="n">i</span> <span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">indegree</span><span class="p">)</span> <span class="k">if</span> <span class="n">x</span> <span class="o">==</span> <span class="mi">0</span><span class="p">]</span>
        <span class="n">node_list</span> <span class="o">=</span> <span class="n">deque</span><span class="p">(</span><span class="n">node_list</span><span class="p">)</span>
        <span class="k">while</span> <span class="n">node_list</span><span class="p">:</span>
            <span class="n">node</span> <span class="o">=</span> <span class="n">node_list</span><span class="p">.</span><span class="n">popleft</span><span class="p">()</span>
            <span class="k">if</span> <span class="n">is_visited</span><span class="p">[</span><span class="n">node</span><span class="p">]:</span>
                <span class="k">continue</span>
            <span class="n">is_visited</span><span class="p">[</span><span class="n">node</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span>

            <span class="k">if</span> <span class="n">node</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">adj</span><span class="p">:</span>
                <span class="k">continue</span>
            
            <span class="k">for</span> <span class="n">next_node</span> <span class="ow">in</span> <span class="n">adj</span><span class="p">[</span><span class="n">node</span><span class="p">]:</span>
                <span class="n">indegree</span><span class="p">[</span><span class="n">next_node</span><span class="p">]</span> <span class="o">-=</span> <span class="mi">1</span>
                <span class="k">if</span> <span class="n">indegree</span><span class="p">[</span><span class="n">next_node</span><span class="p">]</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
                    <span class="n">node_list</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">next_node</span><span class="p">)</span>

        <span class="k">return</span> <span class="nb">sum</span><span class="p">(</span><span class="n">is_visited</span><span class="p">)</span> <span class="o">==</span> <span class="n">numCourses</span>
</code></pre></div></div>]]></content><author><name>melonicedlatte</name></author><category term="Algorithm" /><summary type="html"><![CDATA[1. Problem 207. Course Schedule There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1. Return true if you can finish all courses. Otherwise, return false. Example 1: Input: numCourses = 2, prerequisites = [[1,0]] Output: true Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. Example 2: Input: numCourses = 2, prerequisites = [[1,0],[0,1]] Output: false Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. Constraints: 1 &lt;= numCourses &lt;= 2000 0 &lt;= prerequisites.length &lt;= 5000 prerequisites[i].length == 2 0 &lt;= ai, bi &lt; numCourses All the pairs prerequisites[i] are unique. 2. Solution I solved this problem like this. This problem is related to topological sorting. Check nodes adj node. I used dictionary. Check nodes indegree. I used list. Check nodes that each node’s indegree is 0. I put all 0 indegree nodes on deque. While deque is empty, pop node and renew is_visited. Check that node’s adj and decrease the indegree value by 1. If sum(is_visited) == numCourses means that i can visit all nodes, that means there is no cycle. class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -&gt; bool: adj = {} indegree = [0] * numCourses is_visited = [0] * numCourses for second, first in prerequisites: indegree[second] += 1 if first not in adj: adj[first] = [] adj[first].append(second) node_list = [i for i, x in enumerate(indegree) if x == 0] node_list = deque(node_list) while node_list: node = node_list.popleft() if is_visited[node]: continue is_visited[node] = 1 if node not in adj: continue for next_node in adj[node]: indegree[next_node] -= 1 if indegree[next_node] == 0: node_list.append(next_node) return sum(is_visited) == numCourses]]></summary></entry><entry><title type="html">[leetcode] 49. Group Anagrams _ Algorithm Problem Solve for python</title><link href="https://melonicedlatte.com/2023/11/19/174000.html" rel="alternate" type="text/html" title="[leetcode] 49. Group Anagrams _ Algorithm Problem Solve for python" /><published>2023-11-19T00:00:00+09:00</published><updated>2023-11-19T00:00:00+09:00</updated><id>https://melonicedlatte.com/2023/11/19/174000</id><content type="html" xml:base="https://melonicedlatte.com/2023/11/19/174000.html"><![CDATA[<h2 id="1-problem">1. Problem</h2>

<p><a href="https://leetcode.com/problems/group-anagrams/">49. Group Anagrams</a></p>

<p>Given an array of strings strs, group the anagrams together. You can return the answer in any order.</p>

<p>An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.</p>

<p><strong>Example 1:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
</code></pre></div></div>

<p><strong>Example 2:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Input: strs = [""]
Output: [[""]]
</code></pre></div></div>

<p><strong>Example 3:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Input: strs = ["a"]
Output: [["a"]]
</code></pre></div></div>

<p><strong>Constraints:</strong></p>

<ul>
  <li>1 &lt;= strs.length &lt;= 10^4</li>
  <li>0 &lt;= strs[i].length &lt;= 100</li>
  <li>strs[i] consists of lowercase English letters.</li>
</ul>

<h2 id="2-solution">2. Solution</h2>

<p>I solved this problem like this.</p>

<ul>
  <li>Put s value(each str == s) on dic. The key is sorted(s).</li>
  <li>Put dic values on ans list.</li>
</ul>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Solution</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">groupAnagrams</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">strs</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="nb">str</span><span class="p">])</span> <span class="o">-&gt;</span> <span class="n">List</span><span class="p">[</span><span class="n">List</span><span class="p">[</span><span class="nb">str</span><span class="p">]]:</span>
        <span class="n">dic</span> <span class="o">=</span> <span class="p">{}</span>
        <span class="k">for</span> <span class="n">s</span> <span class="ow">in</span> <span class="n">strs</span><span class="p">:</span>
            <span class="n">key</span> <span class="o">=</span> <span class="s">''</span><span class="p">.</span><span class="n">join</span><span class="p">(</span><span class="nb">sorted</span><span class="p">(</span><span class="n">s</span><span class="p">))</span>
            <span class="k">if</span> <span class="n">key</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">dic</span><span class="p">:</span>
                <span class="n">dic</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="p">[]</span>
            <span class="n">dic</span><span class="p">[</span><span class="n">key</span><span class="p">].</span><span class="n">append</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
        
        <span class="n">ans</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">dic</span><span class="p">:</span>
            <span class="n">ans</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">dic</span><span class="p">[</span><span class="n">key</span><span class="p">])</span>

        <span class="k">return</span> <span class="n">ans</span>
</code></pre></div></div>]]></content><author><name>melonicedlatte</name></author><category term="Algorithm" /><summary type="html"><![CDATA[1. Problem 49. Group Anagrams Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Example 1: Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]] Example 2: Input: strs = [""] Output: [[""]] Example 3: Input: strs = ["a"] Output: [["a"]] Constraints: 1 &lt;= strs.length &lt;= 10^4 0 &lt;= strs[i].length &lt;= 100 strs[i] consists of lowercase English letters. 2. Solution I solved this problem like this. Put s value(each str == s) on dic. The key is sorted(s). Put dic values on ans list. class Solution: def groupAnagrams(self, strs: List[str]) -&gt; List[List[str]]: dic = {} for s in strs: key = ''.join(sorted(s)) if key not in dic: dic[key] = [] dic[key].append(s) ans = [] for key in dic: ans.append(dic[key]) return ans]]></summary></entry><entry><title type="html">[leetcode] 209. Minimum Size Subarray Sum _ Algorithm Problem Solve for python</title><link href="https://melonicedlatte.com/2023/11/19/182000.html" rel="alternate" type="text/html" title="[leetcode] 209. Minimum Size Subarray Sum _ Algorithm Problem Solve for python" /><published>2023-11-19T00:00:00+09:00</published><updated>2023-11-19T00:00:00+09:00</updated><id>https://melonicedlatte.com/2023/11/19/182000</id><content type="html" xml:base="https://melonicedlatte.com/2023/11/19/182000.html"><![CDATA[<h2 id="1-problem">1. Problem</h2>

<p><a href="https://leetcode.com/problems/minimum-size-subarray-sum/">209. Minimum Size Subarray Sum</a></p>

<p>Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.</p>

<p><strong>Example 1:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.
</code></pre></div></div>

<p><strong>Example 2:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Input: target = 4, nums = [1,4,4]
Output: 1
</code></pre></div></div>

<p><strong>Example 3:</strong></p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Input: target = 11, nums = [1,1,1,1,1,1,1,1]
Output: 0
</code></pre></div></div>

<p><strong>Constraints:</strong></p>

<ul>
  <li>1 &lt;= target &lt;= 10^9</li>
  <li>1 &lt;= nums.length &lt;= 10^5</li>
  <li>1 &lt;= nums[i] &lt;= 10^4</li>
</ul>

<h2 id="2-solution">2. Solution</h2>

<p>I solved this problem like this.</p>

<h3 id="21-time-over-solution">2.1. Time over solution</h3>

<ul>
  <li>I first solved this problem like this.</li>
  <li>I check all length of sum and this time complexity is O(n^2).</li>
  <li>n’s max value is 10^5, so this makes problem.</li>
</ul>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Solution</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">minSubArrayLen</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">target</span><span class="p">:</span> <span class="nb">int</span><span class="p">,</span> <span class="n">nums</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="nb">int</span><span class="p">])</span> <span class="o">-&gt;</span> <span class="nb">int</span><span class="p">:</span>
        <span class="k">for</span> <span class="n">l</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">nums</span><span class="p">)</span><span class="o">+</span><span class="mi">1</span><span class="p">):</span>
            <span class="n">value</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">(</span><span class="n">nums</span><span class="p">[:</span><span class="n">l</span><span class="p">])</span>
            <span class="c1"># check value
</span>            <span class="k">if</span> <span class="n">value</span> <span class="o">&gt;=</span> <span class="n">target</span><span class="p">:</span>
                <span class="k">return</span> <span class="n">l</span>

            <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">nums</span><span class="p">)</span><span class="o">-</span><span class="n">l</span><span class="p">):</span>
                <span class="c1"># value change
</span>                <span class="n">value</span> <span class="o">=</span> <span class="n">value</span> <span class="o">-</span> <span class="n">nums</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">+</span> <span class="n">nums</span><span class="p">[</span><span class="n">i</span><span class="o">+</span><span class="n">l</span><span class="p">]</span>

                <span class="c1"># check value
</span>                <span class="k">if</span> <span class="n">value</span> <span class="o">&gt;=</span> <span class="n">target</span><span class="p">:</span>
                    <span class="k">return</span> <span class="n">l</span>

        <span class="k">return</span> <span class="mi">0</span>
</code></pre></div></div>

<h3 id="22-good-solution">2.2. Good solution</h3>

<ul>
  <li>This solution used ‘Sliding window’. I I was greatly helped by <a href="https://leetcode.com/problems/minimum-size-subarray-sum/solutions/277445/python-sliding-window-approach-with-comments/?envType=study-plan-v2&amp;envId=top-interview-150">AnthonyChao’s solution</a>. Thank you so much!</li>
  <li>This solution works like this. The time complexity is just O(n).</li>
  <li>If <code class="language-plaintext highlighter-rouge">sum between right and left &gt;= target</code>, move left cursor</li>
  <li>Else, move right cursor.</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[2,3,1,2,4,3] total = 2,  left = 0, right = 0, ans = 987654321
 ^
[2,3,1,2,4,3] total = 5,  left = 0, right = 1, ans = 987654321
 ^ ^
[2,3,1,2,4,3] total = 6,  left = 0, right = 2, ans = 987654321
 ^   ^
[2,3,1,2,4,3] total = 8,  left = 0, right = 3, ans = 4
 ^     ^
[2,3,1,2,4,3] total = 6,  left = 1, right = 3, ans = 4
   ^   ^
[2,3,1,2,4,3] total = 10, left = 1, right = 4, ans = 4
   ^     ^
[2,3,1,2,4,3] total = 7,  left = 2, right = 4, ans = 4
     ^   ^
[2,3,1,2,4,3] total = 6,  left = 3, right = 4, ans = 4
       ^ ^
[2,3,1,2,4,3] total = 9,  left = 3, right = 5, ans = 4
       ^   ^
[2,3,1,2,4,3] total = 7,  left = 4, right = 5, ans = 2
         ^ ^
</code></pre></div></div>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Solution</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">minSubArrayLen</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">target</span><span class="p">:</span> <span class="nb">int</span><span class="p">,</span> <span class="n">nums</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="nb">int</span><span class="p">])</span> <span class="o">-&gt;</span> <span class="nb">int</span><span class="p">:</span>
        <span class="n">ans</span> <span class="o">=</span> <span class="mi">987654321</span>
        <span class="n">left</span><span class="p">,</span> <span class="n">total</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span>
        
        <span class="k">for</span> <span class="n">right</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">nums</span><span class="p">)):</span>
            <span class="n">total</span> <span class="o">+=</span> <span class="n">nums</span><span class="p">[</span><span class="n">right</span><span class="p">]</span>
            <span class="k">while</span> <span class="n">total</span> <span class="o">&gt;=</span> <span class="n">target</span><span class="p">:</span>
                <span class="n">ans</span> <span class="o">=</span> <span class="nb">min</span><span class="p">(</span><span class="n">ans</span><span class="p">,</span> <span class="n">right</span> <span class="o">-</span> <span class="n">left</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span>
                <span class="n">total</span> <span class="o">-=</span> <span class="n">nums</span><span class="p">[</span><span class="n">left</span><span class="p">]</span>
                <span class="n">left</span> <span class="o">+=</span> <span class="mi">1</span>
        
        <span class="k">return</span> <span class="n">ans</span> <span class="k">if</span> <span class="n">ans</span> <span class="o">!=</span> <span class="mi">987654321</span> <span class="k">else</span> <span class="mi">0</span>
</code></pre></div></div>]]></content><author><name>melonicedlatte</name></author><category term="Algorithm" /><summary type="html"><![CDATA[1. Problem 209. Minimum Size Subarray Sum Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead. Example 1: Input: target = 7, nums = [2,3,1,2,4,3] Output: 2 Explanation: The subarray [4,3] has the minimal length under the problem constraint. Example 2: Input: target = 4, nums = [1,4,4] Output: 1 Example 3: Input: target = 11, nums = [1,1,1,1,1,1,1,1] Output: 0 Constraints: 1 &lt;= target &lt;= 10^9 1 &lt;= nums.length &lt;= 10^5 1 &lt;= nums[i] &lt;= 10^4 2. Solution I solved this problem like this. 2.1. Time over solution I first solved this problem like this. I check all length of sum and this time complexity is O(n^2). n’s max value is 10^5, so this makes problem. class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -&gt; int: for l in range(1, len(nums)+1): value = sum(nums[:l]) # check value if value &gt;= target: return l for i in range(0, len(nums)-l): # value change value = value - nums[i] + nums[i+l] # check value if value &gt;= target: return l return 0 2.2. Good solution This solution used ‘Sliding window’. I I was greatly helped by AnthonyChao’s solution. Thank you so much! This solution works like this. The time complexity is just O(n). If sum between right and left &gt;= target, move left cursor Else, move right cursor. [2,3,1,2,4,3] total = 2, left = 0, right = 0, ans = 987654321 ^ [2,3,1,2,4,3] total = 5, left = 0, right = 1, ans = 987654321 ^ ^ [2,3,1,2,4,3] total = 6, left = 0, right = 2, ans = 987654321 ^ ^ [2,3,1,2,4,3] total = 8, left = 0, right = 3, ans = 4 ^ ^ [2,3,1,2,4,3] total = 6, left = 1, right = 3, ans = 4 ^ ^ [2,3,1,2,4,3] total = 10, left = 1, right = 4, ans = 4 ^ ^ [2,3,1,2,4,3] total = 7, left = 2, right = 4, ans = 4 ^ ^ [2,3,1,2,4,3] total = 6, left = 3, right = 4, ans = 4 ^ ^ [2,3,1,2,4,3] total = 9, left = 3, right = 5, ans = 4 ^ ^ [2,3,1,2,4,3] total = 7, left = 4, right = 5, ans = 2 ^ ^ class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -&gt; int: ans = 987654321 left, total = 0, 0 for right in range(len(nums)): total += nums[right] while total &gt;= target: ans = min(ans, right - left + 1) total -= nums[left] left += 1 return ans if ans != 987654321 else 0]]></summary></entry></feed>