일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- 생성형AI
- 빅데이터
- Python
- 클라우드
- 코드업파이썬
- 파이썬알고리즘
- gcp
- Python3
- 자연어처리
- GenerativeAI
- nlp
- C#
- Azure
- codeup
- 파이썬기초100제
- 머신러닝
- Blazor
- 투포인터
- 구글퀵랩
- GenAI
- 파이썬기초
- Microsoft
- TwoPointer
- LeetCode
- 릿코드
- 알고리즘
- 파이썬
- 리트코드
- 코드업
- 데이터사이언스
- Today
- Total
목록리트코드 (11)
Tech for good

1️⃣번째 방법class Solution: def reverseWords(self, s: str) -> str: return " ".join(s.split()[::-1]) 시간 복잡도 및 공간 복잡도시간 복잡도: O(n)split() → O(n)[::-1] (리스트 뒤집기) → O(n)" ".join() → O(n)따라서 전체 시간 복잡도는 O(n) 입니다.공간 복잡도: O(n)split()이 새로운 리스트를 생성하므로 O(n)의 추가 공간이 필요합니다.2️⃣번째 방법Follow-up: O(1) 추가 공간으로 해결할 수 있을까?문자열이 가변(mutable)한 경우, O(1) 공간에서 In-place 방식으로 해결할 수 있습니다.파이썬에서는 문자열이 **불변(immutable)**이라서 ..

class Solution: def isSubsequence(self, s: str, t: str) -> bool: i, j = 0, 0 # Pointers for s and t while i i += 1 -> s의 인덱스를 증가j += 1 -> s와 상관없이 (즉, 매치됨과 상관없이) t의 인덱스를 하나씩 증가 Example 2의 경우, x가 t에 없으므로 i False시간 복잡도 및 공간 복잡도시간 복잡도: O(n) (t의 길이만큼 한 번 순회)공간 복잡도: O(1) (추가적인 공간 사용 없음)

class Solution: def isPrefixOfWord(self, sentence: str, searchWord: str) -> int: words = sentence.split() for i, word in enumerate(words): if word.startwith(searchword): return i+1 return -1Explanation:Split the Sentence: The input sentence is split into a list of words using .split(), which automatically handles single spaces.Iterate Over Words:..

🔹 문제 풀이 접근이 문제는 최소한의 거래로 모든 부채를 정산하는 문제이다.즉, 누가 누구에게 돈을 줘야 하는지 최소한의 거래(transactions)로 해결하는 것이 목표이다.✅ 해결 방법: Backtracking 각 사람의 최종 잔액을 계산주어진 거래를 기반으로 각 사람의 순 잔액(balance)을 계산.예를 들어, 어떤 사람이 $10 빌려줬으면 +10, $5 빌렸으면 -5.잔액이 0이 아닌 사람들을 대상으로 최소 거래 조합 찾기부채(- 잔액)와 자산(+ 잔액)을 매칭하여 최소 거래로 해결.백트래킹(Backtracking)을 활용하여 모든 가능한 거래를 탐색.from collections import defaultdictclass Solution: def minTransfers(self, tr..

https://leetcode.com/problems/median-of-two-sorted-arrays/description/ 🔹 문제 풀이 접근이 문제는 두 개의 정렬된 배열(nums1, nums2)이 주어질 때, 병합 후 중앙값(median)을 찾는 문제이다. ✅ 최적화 방법 (이진 탐색 활용)이진 탐색(Binary Search)을 사용하여 한 배열을 절반으로 분할하면서 답을 찾음.시간 복잡도: O(log(min(m, n)))class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: # nums1이 항상 짧은 배열이 되도록 보장 if len(nums1) > l..

알고리즘:주어진 문자열을 파싱하여 문자 -> 빈도 형태로 해시맵에 저장해시맵의 키(문자)를 알파벳 순으로 정렬최종 결과 문자열을 생성from collections import defaultdictclass Solution: def betterCompression(self, compressed: str) -> str: freq_map = defaultdict(int) i = 0 n = len(compressed) # 문자열을 순회하면서 문자와 숫자 파싱 while i 🔹 시간 복잡도:문자열을 한 번 순회하면서 파싱 (O(N))해시맵을 정렬 (O(K log K), K는 문자 종류의 개수, 최대 26)결과 생성 (O(K))총..

class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ low, mid, high = 0, 0, len(nums) - 1 # 세 개의 포인터 설정 while mid 코드 설명low, mid, high 세 개의 포인터를 사용하여 배열을 정렬한다.초기 설정low: 0을 배치할 위치mid: 현재 검사 중인 위치high: 2를 배치할 위치while 반복문 (mid ≤ high)nums[mid] == 0 (빨간색)low와 mid를 swap하고 low와 mid를 증가nums[mid..

class Solution: def moveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ non_zero_index = 0 # 배열을 처음부터 끝까지 순회하면서 0이 아닌 요소를 앞으로 이동 for i in range(len(nums)): if nums[i] != 0: # 현재 숫자(nums[i])와 non_zero_index 위치의 숫자를 스왑 nums[non_zero_index], nums[i] = nums[i..

이 문제를 한 번의 순회(One-pass)로 해결하는 방법은 두 개의 포인터(first, second)를 사용하는 것이다.first 포인터를 먼저 n칸 이동시킨 후, second 포인터를 first와 함께 이동하면 first가 끝에 도달했을 때 second는 삭제할 노드의 직전 노드를 가리키게 된다.✅ 알고리즘 풀이 (Two Pointer)더미 노드 추가: 삭제할 노드가 head일 수도 있으므로 더미 노드를 추가.first 포인터 선행 이동: first를 n칸 먼저 이동.두 포인터 이동: first가 리스트의 끝에 도달할 때까지 second와 함께 이동.노드 삭제: second.next를 second.next.next로 변경하여 노드 삭제.새로운 head 반환: dummy.next를 반환.# Defini..
해시셋(Hash Set) 활용 -중복을 방지하면서 각 노드를 탐색할 때 (k - 현재 노드 값)이 존재하는지 확인하는 방법. 설명dfs 함수를 사용하여 트리를 깊이 우선 탐색(DFS) 한다.각 노드를 방문할 때 k - node.val이 seen 집합에 존재하는지 확인한다.존재하면 True를 반환하고, 없으면 현재 노드 값을 seen에 추가한 후 왼쪽과 오른쪽 서브트리를 탐색한다.전체 탐색이 끝날 때까지 조건을 만족하는 쌍이 없으면 False를 반환한다.시간 복잡도각 노드를 한 번씩 방문하므로 O(N) (N은 트리의 노드 개수).공간 복잡도최악의 경우 모든 노드 값을 seen에 저장해야 하므로 O(N). # Definition for a binary tree node.class TreeNode: de..