[LeetCode/Python] 209. Minimum Size Subarray Sum

도니·2025년 9월 29일

Interview-Prep

목록 보기
25/29
post-thumbnail

📌 Problem

[LeetCode] 209. Minimum Size Subarray Sum

📌 Solution

Idea

  • right 포인터를 움직이며 구간 합을 늘리기
  • 합이 target 이상이 되면, left를 움직이며 가능한 한 구간을 줄이고 최소 길이 갱신하기
  • 전체 배열 끝까지 탐색하기

Code

class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        n = len(nums)
        left, total = 0, 0
        ans = n+1

        for right, num in enumerate(nums):
            total += num
            while total >= target:
                ans = min(ans, right - left + 1)
                total -= nums[left]
                left += 1

        return ans if ans != n+1 else 0

Complexity

  • Time Complexity: O(n)O(n)
  • Space Complexity: O(1)O(1)

Cf Sliding Window Simulation

stepright추가값 xcur(구간합)while(cur ≥ 7) 수축 과정갱신된 ans최종 (left,cur)
10227(0,2)
21357(0,5)
32167(0,6)
4328길이 4 → ans=4, cur-=2→64(1,6)
54410길이 4 → ans=4, cur-=3→7 → 길이 3 → ans=3, cur-=1→63(3,6)
6539길이 3 → ans=3, cur-=2→7 → 길이 2 → ans=2, cur-=4→32(5,3)
profile
Where there's a will, there's a way

0개의 댓글