From 50dcab428978c79b72fc06c60a46c600d86721da Mon Sep 17 00:00:00 2001 From: GangBean Date: Sat, 21 Dec 2024 09:03:41 +0900 Subject: [PATCH 001/183] feat: solve two sum --- two-sum/GangBean.java | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 two-sum/GangBean.java diff --git a/two-sum/GangBean.java b/two-sum/GangBean.java new file mode 100644 index 000000000..cd5abf382 --- /dev/null +++ b/two-sum/GangBean.java @@ -0,0 +1,35 @@ +class Solution { + public int[] twoSum(int[] nums, int target) { + /** + 1. understanding + - find the indices where the numbers of that index pair sum upto the target number. + - exactly one solution + - use each element only once + - return in any order + 2. strategy + - brute force: + - validate for all pair sum + - hashtable: + - assing hashtable variable to save the nums and index + - while iterate over the nums, + - calculate the diff, and check if the diff in the hashtable. + - or save new entry. + 3. complexity + - time: O(N) + - space: O(N) + */ + + Map map = new HashMap<>(); + + for (int i = 0; i < nums.length; i++) { + int diff = target - nums[i]; + if (map.containsKey(diff)) { + return new int[] {map.get(diff), i}; + } + map.put(nums[i], i); + } + + return new int[] {}; + } +} + From 88368350c3de8fa37d9e1d032bf6f67306757497 Mon Sep 17 00:00:00 2001 From: eunhwa99 Date: Sat, 21 Dec 2024 19:39:53 +0900 Subject: [PATCH 002/183] two sum --- two-sum/eunhwa99.java | 79 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 two-sum/eunhwa99.java diff --git a/two-sum/eunhwa99.java b/two-sum/eunhwa99.java new file mode 100644 index 000000000..a3af47629 --- /dev/null +++ b/two-sum/eunhwa99.java @@ -0,0 +1,79 @@ +// 문제 요구사항 -> O(n^2) 보다 작은 시간복잡도로 구현 필요 +// 문제를 보자마자 생각난 것 -> 이분탐색 (2 원소 합이 target 인 것을 구해야 하므로) +// 이분 탐색 시간 복잡도 -> 정렬(O(nlogn)) + 이분탐색 (log(n)) -> nlogn +// 공간 복잡도 -> 배열 크기 만큼 공간 필요 (n) + +import java.util.Arrays; +import java.util.HashMap; + +class ValueIndex implements Comparable { + int value; + int index; + + // ValueIndex 객체를 정렬할 때 value 기준으로 오름차순 정렬 + @Override + public int compareTo(ValueIndex other) { + return Integer.compare(this.value, other.value); + } +} + +class Solution { + + public int[] twoSum(int[] nums, int target) { + int size = nums.length; + ValueIndex[] valueIndex = new ValueIndex[size]; + for (int i = 0; i < size; ++i) { + valueIndex[i] = new ValueIndex(); + valueIndex[i].value = nums[i]; + valueIndex[i].index = i; // 정렬 전 original index 저장 + } + Arrays.sort(valueIndex); // 정렬 + int left = 0; + int right = nums.length - 1; + + while (left < right) { + int leftVal = valueIndex[left].value; + int rightVal = valueIndex[right].value; + int sum = leftVal + rightVal; + + if (sum < target) { // target 보다 합이 작으면, left 값이 커져야 함 + left += 1; + } else if (sum > target) { + right -= 1; // target 보다 합이 크면, right 값이 작아져야 함 + } else { // sum = target 이면 끝! + break; + } + } + + return new int[]{valueIndex[left].index, valueIndex[right].index}; + } +} + + +/** + * hashMap을 이용한 O(n) 방법도 있다고 해서 추가 구현해보았습니다. (시간/공간 복잡도 O(n)) + */ + +class Solution { + + public int[] twoSum(int[] nums, int target) { + HashMap numMap = new HashMap<>(); + int left = 0, right = 0; + for (int i = 0; i < nums.length; i++) { + int complement = target - nums[i]; // 현재 숫자와 합쳐서 target을 만드는 숫자 + + // 이미 그 숫자가 해시맵에 있다면, 두 인덱스를 반환 + if (numMap.containsKey(complement)) { + left = numMap.get(complement); + right = i; + break; + } + + // 해시맵에 현재 숫자와 인덱스를 추가 + numMap.put(nums[i], i); + } + + return new int[]{left, right}; + + } +} From 7b9d6ff4e1bd9e8926b95a2b912fccc33fb33f53 Mon Sep 17 00:00:00 2001 From: eunhwa99 Date: Sat, 21 Dec 2024 20:08:22 +0900 Subject: [PATCH 003/183] reverse bits --- reverse-bits/eunhwa99.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 reverse-bits/eunhwa99.java diff --git a/reverse-bits/eunhwa99.java b/reverse-bits/eunhwa99.java new file mode 100644 index 000000000..163ff6614 --- /dev/null +++ b/reverse-bits/eunhwa99.java @@ -0,0 +1,19 @@ +// 풀이방법 +// n의 경우 끝에서부터 비트연산을 해야 하므로 가장 오른쪽부터 시작해야 함 +// 이는 n과 1을 AND 연산하고, n을 오른쪽으로 미루면서 수행하면 된다. (n >> 1) +// 최종 결과를 위한 값은 result에 저장할 예정이다. result의 경우, n과 반대로 왼쪽으로 한 칸씩 미루면서 n의 비트를 삽입해줘야 함 (OR 연산) + +// 시간 복잡도 (숫자의 비트 수 만큼 필요) -> O(N) (N: 숫자 n의 비트 수, 문제에서는 32로 고정) +// 공간 복잡도: (result 변수 크기) +public class Solution { + + public int reverseBits(int n) { + int result = 0; + for (int i = 0; i < 32; i++) { + result = result << 1; + result |= (n & 1); + n = n >> 1; + } + return result; + } +} From 5f2ae965066af8e0604e02217e12bf67950db62f Mon Sep 17 00:00:00 2001 From: eunhwa99 Date: Sat, 21 Dec 2024 20:51:34 +0900 Subject: [PATCH 004/183] product of array except self --- product-of-array-except-self/eunhwa99.java | 35 ++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 product-of-array-except-self/eunhwa99.java diff --git a/product-of-array-except-self/eunhwa99.java b/product-of-array-except-self/eunhwa99.java new file mode 100644 index 000000000..975cc94ba --- /dev/null +++ b/product-of-array-except-self/eunhwa99.java @@ -0,0 +1,35 @@ +// 풀이 +// 현재 인덱스가 i 일 때, 문제에서 구하고자 하는 값은 아래와 같다. +// 나의 왼쪽(i-1)부터 처음까지의 곱 * 나의 오른쪽(i+1)부터 끝까지의 곱 +// leftProduct[i-1] = 왼쪽(i-1)부터 처음까지의 곱 +// rightProduct[i+1] = 오른쪽(i+1)부터 끝까지의 곱 +// leftProduct는 처음부터 i까지 순회하면서 구하면 된다. leftProduct[i] = leftProduct[i-1] * (나 자신 = nums[i]) +// rightProduct는 끝부터 시작해서 i까지 순회하면서 구하면 된다. rightProduct[i] = rightProduct[i+1] * (나 자신 = nums[i]) + + +// DP 를 사용하면 시간 복잡도는 O(N) +// 공간 복잡도는 2개의 배열이 필요하고, 답으로 보낼 배열까지 해서 O(3*N) = O(N) + +class Solution { + public int[] productExceptSelf(int[] nums) { + int len = nums.length; + int[] leftProduct = new int[len]; + int[] rightProduct = new int[len]; + + leftProduct[0] = nums[0]; + rightProduct[len - 1] = nums[len - 1]; + for (int i = 1; i < len; ++i) { + leftProduct[i] = leftProduct[i - 1] * nums[i]; + rightProduct[len - i - 1] = rightProduct[len - i] * nums[len - i - 1]; + } + + int[] result = new int[len]; + result[0] = rightProduct[1]; + result[len - 1] = leftProduct[len - 2]; + for (int i = 1; i < len - 1; ++i) { + result[i] = leftProduct[i - 1] * rightProduct[i + 1]; + } + return result; + } +} + From 1bd51e26c81f89b86fe3fe6bcd47384c5c3e9b94 Mon Sep 17 00:00:00 2001 From: eunhwa99 Date: Sat, 21 Dec 2024 20:52:01 +0900 Subject: [PATCH 005/183] =?UTF-8?q?line=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- reverse-bits/eunhwa99.java | 1 + two-sum/eunhwa99.java | 1 + 2 files changed, 2 insertions(+) diff --git a/reverse-bits/eunhwa99.java b/reverse-bits/eunhwa99.java index 163ff6614..7e2f6ff46 100644 --- a/reverse-bits/eunhwa99.java +++ b/reverse-bits/eunhwa99.java @@ -17,3 +17,4 @@ public int reverseBits(int n) { return result; } } + diff --git a/two-sum/eunhwa99.java b/two-sum/eunhwa99.java index a3af47629..5edf3eede 100644 --- a/two-sum/eunhwa99.java +++ b/two-sum/eunhwa99.java @@ -77,3 +77,4 @@ public int[] twoSum(int[] nums, int target) { } } + From e05461fec88d3e33aa4b3ab8a93b22d050673295 Mon Sep 17 00:00:00 2001 From: minji-go Date: Sat, 21 Dec 2024 21:10:56 +0900 Subject: [PATCH 006/183] refactor: construct binary tree from preorder and inorder traversal - correct complexity --- .../minji-go.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/construct-binary-tree-from-preorder-and-inorder-traversal/minji-go.java b/construct-binary-tree-from-preorder-and-inorder-traversal/minji-go.java index 1f7f3a769..bb5efde92 100644 --- a/construct-binary-tree-from-preorder-and-inorder-traversal/minji-go.java +++ b/construct-binary-tree-from-preorder-and-inorder-traversal/minji-go.java @@ -2,7 +2,7 @@ Problem: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ Description: Given two integer arrays preorder and inorder, construct and return the binary tree. Concept: Array, Hash Table, Divide and Conquer, Tree, Binary Tree - Time Complexity: O(NM), Runtime 2ms + Time Complexity: O(N²), Runtime 2ms Space Complexity: O(N), Memory 45.02MB */ import java.util.HashMap; From 8ca1cc0865d3c70c6bc0b2bb860a1396eef1be90 Mon Sep 17 00:00:00 2001 From: minji-go Date: Sun, 22 Dec 2024 01:03:28 +0900 Subject: [PATCH 007/183] feat: two sum --- two-sum/minji-go.java | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 two-sum/minji-go.java diff --git a/two-sum/minji-go.java b/two-sum/minji-go.java new file mode 100644 index 000000000..8464665fd --- /dev/null +++ b/two-sum/minji-go.java @@ -0,0 +1,21 @@ +/* + Problem: https://leetcode.com/problems/two-sum/ + Description: return indices of the two numbers such that they add up to target. not use the same element twice. + Topics: Array, Hash Table + Time Complexity: O(N), Runtime 2ms + Space Complexity: O(N), Memory 45.1MB +*/ +class Solution { + public int[] twoSum(int[] nums, int target) { + Map numIndex = new HashMap<>(); + for(int secondIndex=0; secondIndex Date: Sun, 22 Dec 2024 01:03:41 +0900 Subject: [PATCH 008/183] feat: reverse bits --- reverse-bits/minji-go.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 reverse-bits/minji-go.java diff --git a/reverse-bits/minji-go.java b/reverse-bits/minji-go.java new file mode 100644 index 000000000..de134e9db --- /dev/null +++ b/reverse-bits/minji-go.java @@ -0,0 +1,19 @@ +/* + Problem: https://leetcode.com/problems/reverse-bits/ + Description: Reverse bits of a given 32 bits unsigned integer + Topics: Divide and Conquer, Bit Manipulation + Time Complexity: O(1), Runtime 1ms + Space Complexity: O(1), Memory 41.72MB +*/ +public class Solution { + public int reverseBits(int n) { + long unsignedNum = n > 0 ? n : n + 2 * (long) Math.pow(2,31); //= Integer.toUnsignedLong() + + int reversedNum = 0; + for(int i=31; i>=0; i--){ + if(unsignedNum % 2 == 1) reversedNum += (long) Math.pow(2,i); //= (1< Date: Sun, 22 Dec 2024 17:24:25 +0900 Subject: [PATCH 009/183] [Week3](gmlwls96) two-sum --- two-sum/gmlwls96.kt | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 two-sum/gmlwls96.kt diff --git a/two-sum/gmlwls96.kt b/two-sum/gmlwls96.kt new file mode 100644 index 000000000..9f304bb14 --- /dev/null +++ b/two-sum/gmlwls96.kt @@ -0,0 +1,5 @@ +class Solution { + fun twoSum(nums: IntArray, target: Int): IntArray { + + } +} From 471cb9d4c43715564bc5df358d1a0c50453c8a9f Mon Sep 17 00:00:00 2001 From: Heejin Ham Date: Sun, 22 Dec 2024 18:33:40 +0900 Subject: [PATCH 010/183] [Week3](gmlwls96) two-sum code. --- two-sum/gmlwls96.kt | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/two-sum/gmlwls96.kt b/two-sum/gmlwls96.kt index 9f304bb14..5d7091c50 100644 --- a/two-sum/gmlwls96.kt +++ b/two-sum/gmlwls96.kt @@ -1,5 +1,29 @@ class Solution { + // 시간 : O(logN), 공간(2N) fun twoSum(nums: IntArray, target: Int): IntArray { + val sortNums = List(nums.size) { listOf(nums[it], it) }.sortedBy { it[0] } + // 1. list( list('값', 'index')) 형태의 list를 만들고 값을 기준으로 정렬한다. + var i = 0 + var j = sortNums.lastIndex + // 2. 2포인터 방식으로 두 값을 합했을때 target이 되는 값을 찾는다. + while (i < j) { + val sum = sortNums[i][0] + sortNums[j][0] + when { + sum == target -> { // target과 sum이 일치할시 바로 return. + return intArrayOf( + min(sortNums[i][1], sortNums[j][1]), + max(sortNums[i][1], sortNums[j][1]) + ) + } + sum < target -> { // sum이 target보다 값이 작은경우 i를 한칸씩 더한다. + i++ + } + sum > target -> { // sum이 target보다 값이 큰경우 j를 한칸씩 내린다. + j-- + } + } + } + return intArrayOf() } } From 26b6991c80785ae518363ff6bf7b40373ff10dd7 Mon Sep 17 00:00:00 2001 From: Heejin Ham Date: Sun, 22 Dec 2024 21:23:30 +0900 Subject: [PATCH 011/183] [Week3](gmlwls96) reverse-bits --- reverse-bits/gmlwls96.kt | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 reverse-bits/gmlwls96.kt diff --git a/reverse-bits/gmlwls96.kt b/reverse-bits/gmlwls96.kt new file mode 100644 index 000000000..7f12a7552 --- /dev/null +++ b/reverse-bits/gmlwls96.kt @@ -0,0 +1,14 @@ +class Solution { + // you need treat n as an unsigned value + fun reverseBits(n: Int): Int { + var bitString = Integer.toBinaryString(n) + bitString = CharArray(32 - bitString.length) { '0' }.concatToString() + bitString + var result = 0 + var scale = 1 + bitString.forEach { + result += it.digitToInt() * scale + scale *= 2 + } + return result + } +} From 5d7ed3f96fc8cbafcae9c1aea5a2ac16536345af Mon Sep 17 00:00:00 2001 From: Taewan Lim Date: Mon, 23 Dec 2024 00:12:44 +0900 Subject: [PATCH 012/183] two-sum --- two-sum/taewanseoul.ts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 two-sum/taewanseoul.ts diff --git a/two-sum/taewanseoul.ts b/two-sum/taewanseoul.ts new file mode 100644 index 000000000..783225776 --- /dev/null +++ b/two-sum/taewanseoul.ts @@ -0,0 +1,21 @@ +/** + * 1. Two Sum + * Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. + * You may assume that each input would have exactly one solution, and you may not use the same element twice. + * You can return the answer in any order. + * + * https://leetcode.com/problems/two-sum/description/ + */ +function twoSum(nums: number[], target: number): number[] { + const map = new Map(); + + for (let i = 0; i < nums.length; i++) { + if (map.has(target - nums[i])) { + return [i, map.get(target - nums[i])!]; + } + map.set(nums[i], i); + } +} + +// O(n) time +// O(n) space From 116ad02ff377d437a0decf3221f931300f4e4494 Mon Sep 17 00:00:00 2001 From: Nayeon Date: Mon, 23 Dec 2024 07:35:51 +0900 Subject: [PATCH 013/183] Add placeholder file for 'Two Sum' problem --- two-sum/KwonNayeon.py | 1 + 1 file changed, 1 insertion(+) create mode 100644 two-sum/KwonNayeon.py diff --git a/two-sum/KwonNayeon.py b/two-sum/KwonNayeon.py new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/two-sum/KwonNayeon.py @@ -0,0 +1 @@ + From 2fc5ef0ffcd47ac9133fed2b09a41dd17860a93b Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Mon, 23 Dec 2024 07:38:13 +0900 Subject: [PATCH 014/183] feat: [Week 03-1] solve two-sum --- two-sum/Chaedie.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 two-sum/Chaedie.py diff --git a/two-sum/Chaedie.py b/two-sum/Chaedie.py new file mode 100644 index 000000000..f9acf694a --- /dev/null +++ b/two-sum/Chaedie.py @@ -0,0 +1,21 @@ +""" +Solution: + Use a hash map to store numbers and their indices + Iterate through the list and check if difference between target and val + return the index list + +Time: O(n) +Space: O(n) + +""" + + +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + num_map = {} # num : index + + for i, val in enumerate(nums): + diff = target - val + if diff in num_map: + return [num_map[diff], i] + num_map[val] = i From dc8c1210aec7b6050ba5e7b91aee435a58af1dc8 Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Mon, 23 Dec 2024 07:50:14 +0900 Subject: [PATCH 015/183] feat: [Week 03-2] solve reverse-bits --- reverse-bits/Chaedie.py | 50 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 reverse-bits/Chaedie.py diff --git a/reverse-bits/Chaedie.py b/reverse-bits/Chaedie.py new file mode 100644 index 000000000..8b603198d --- /dev/null +++ b/reverse-bits/Chaedie.py @@ -0,0 +1,50 @@ +""" +1. 학습은 진행했지만, 스스로 완벽하게 풀지 못했습니다. + 다음주에 bit 연산으로 다시 풀어볼 예정입니다. +""" + + +class Solution: + + # 알고달레 풀이 1) Stack + def reverseBits(self, n: int) -> int: + stack = [] + while len(stack) < 32: + stack.append(n % 2) + n //= 2 + + result, scale = 0, 1 + while stack: + result += stack.pop() * scale + scale *= 2 + return result + + # 알고달레 풀이 2) bit manipulation + def reverseBits(self, n: int) -> int: + result = 0 + print(n) + for i in range(32): + print(result) + result <<= 1 + result |= n & 1 + n >>= 1 + return result + + # NeetCode 풀이 + def reverseBits(self, n: int) -> int: + res = 0 + + for i in range(32): + bit = (n >> i) & 1 + res = res | (bit << (31 - i)) + return res + + # 스스로 풀기 + # 한번 더 풀 에정입니다. + def reverseBits(self, n: int) -> int: + result = 0 + for i in range(32): + result = result << 1 + result = result | (n & 1) + n = n >> 1 + return result From 3d25456f2dd266d44a71c915238daefc549d28de Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Mon, 23 Dec 2024 07:53:21 +0900 Subject: [PATCH 016/183] feat: [Week 03-3] solve product-of-array-except-self --- product-of-array-except-self/Chaedie.py | 65 +++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 product-of-array-except-self/Chaedie.py diff --git a/product-of-array-except-self/Chaedie.py b/product-of-array-except-self/Chaedie.py new file mode 100644 index 000000000..25876217e --- /dev/null +++ b/product-of-array-except-self/Chaedie.py @@ -0,0 +1,65 @@ +""" +solution 1: + 왼쪽부터 곱해가는 prefix, + 오른쪽부터 곱해가는 postfix, + 2가지의 배열을 만든다. + + nums = [1,2,3,4] + prefix = [1,2,6,24] + postfix = [24,12,4,1] + + 이후 정답 배열 result[i] = prefix[i - 1] * postfix[i + 1] 이 되도록 만든다. + 0, n-1 번째 인덱스에선 예외처리를 해준다. + +Time: O(n) = prefix 계산 O(n) + postfix 계산 O(n) + result 계산 O(n) +Space: O(n) = prefix 배열 O(n) + postfix 배열 O(n) +""" + +# class Solution: +# def productExceptSelf(self, nums: List[int]) -> List[int]: +# n = len(nums) + +# prefix = [1 for i in range(n)] +# postfix = [1 for i in range(n)] + +# prefix[0] = nums[0] +# for i in range(1, n): +# prefix[i] = prefix[i-1] * nums[i] + +# postfix[n - 1] = nums[n - 1] +# for i in range(n-2, -1, -1): +# postfix[i] = postfix[i + 1] * nums[i] + +# result = [] +# for i in range(n): +# pre = prefix[i - 1] if i - 1 >= 0 else 1 +# post = postfix[i + 1] if i + 1 < n else 1 +# result.append(pre * post) +# return result + +""" +최적화 풀이 +Solution: + prefix, postfix 배열 저장 없이 순회하며 바로 prefix, postfix 를 곱해서 result 배열에 담는다. + +Time: O(n) = O(2n) +Space: O(1) +""" + + +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + n = len(nums) + result = [1] * n + + prefix = 1 + for i in range(n): + result[i] *= prefix + prefix *= nums[i] + + postfix = 1 + for i in range(n - 1, -1, -1): + result[i] *= postfix + postfix *= nums[i] + + return result From c5b614d0c5abfb3b9051d6800f5a80310c986def Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Mon, 23 Dec 2024 08:09:48 +0900 Subject: [PATCH 017/183] feat: [Week 03-4] solve combination-sum --- combination-sum/Chaedie.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 combination-sum/Chaedie.py diff --git a/combination-sum/Chaedie.py b/combination-sum/Chaedie.py new file mode 100644 index 000000000..5cf765c6d --- /dev/null +++ b/combination-sum/Chaedie.py @@ -0,0 +1,35 @@ +""" +Solution: + 최초 풀이 당시엔 단순히 dfs로 풀었으나 시간 초과로 실패했습니다. + 이후 풀이 설명을 통해 i 번째 숫자를 넣거나 / 안넣거나 라는 조건으로 i를 늘려가도록 진행하는 백트래킹을 하면 된다는점을 배웠습니다. + 이를 통해 불필요한 중복을 줄이고 효율적인 구현이 가능해집니다. + +C: len(candidates) +T: target size + +Time: O(C^T) = 라고 설명되어 있는데 솔찍히 잘 모르겠습니다. +Space: O(T) = 재귀가 가장 깊을 때 [1,1,1,1...] T 만큼이기 때문에 O(T) +""" + + +class Solution: + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + result = [] + sol = [] + n = len(candidates) + + def backtrack(i, cur_sum): + if cur_sum == target: + result.append(sol.copy()) + return + if cur_sum > target or i == n: + return + + backtrack(i + 1, cur_sum) + + sol.append(candidates[i]) + backtrack(i, cur_sum + candidates[i]) + sol.pop() + + backtrack(0, 0) + return result From 04b8deb8dbce5c2b3ef61b2a51817b8b17b0ac23 Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Mon, 23 Dec 2024 08:57:07 +0900 Subject: [PATCH 018/183] feat: [Week 03-5] solve maximum-subarray --- maximum-subarray/Chaedie.py | 64 +++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 maximum-subarray/Chaedie.py diff --git a/maximum-subarray/Chaedie.py b/maximum-subarray/Chaedie.py new file mode 100644 index 000000000..f65a1ebb7 --- /dev/null +++ b/maximum-subarray/Chaedie.py @@ -0,0 +1,64 @@ +""" +Solution1: + sliding window 일 것 같지만 구현이 어려워 일단 Brute Force 부터 진행합니다. + -> 시간 초과로 실패 + +Time: O(n^2) = n(for) * n(for) +Space: O(n) = cur 배열 +""" + + +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + n = len(nums) + max_sum = float(-inf) + for i in range(n): + cur = [] + cur_sum = 0 + for j in range(i, n): + cur_sum += nums[j] + cur.append(nums[j]) + max_sum = max(max_sum, cur_sum) + return max_sum + + +""" +Solution2: + Sliding Window로 풀 수 있을거라 생각했는데 잘 안되었습니다. +""" + + +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + n = len(nums) + max_sum = float(-inf) + + l = 0 + window = 0 + for r in range(n): + window += nums[r] + max_sum = max(max_sum, window) + while max_sum < window: + l += 1 + + return max_sum + + +""" +Solution3 - 알고달레: + 솔루션을 통해 학습했습니다. + 이해가 어려워 다시 풀어볼 예정입니다. + +Time: O(n) +Space: O(1) +""" + + +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + max_sum = nums[0] + cur_sum = 0 + for num in nums: + cur_sum = max(cur_sum + num, num) + max_sum = max(cur_sum, max_sum) + return max_sum From 7bc8735086db69b43eefa3b851f0e261e3147f7e Mon Sep 17 00:00:00 2001 From: mmyeon Date: Mon, 23 Dec 2024 11:34:51 +0900 Subject: [PATCH 019/183] add solution : 1. Two Sum --- two-sum/mmyeon.ts | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 two-sum/mmyeon.ts diff --git a/two-sum/mmyeon.ts b/two-sum/mmyeon.ts new file mode 100644 index 000000000..3b3d8603f --- /dev/null +++ b/two-sum/mmyeon.ts @@ -0,0 +1,31 @@ +/** + * + * 접근 방법 : + * - 이미 방문한 숫자와 인덱스를 맵에 저장 + * - nums 배열 순회하면서, 찾는 숫자 가 없으면 맵에 값, 인덱스 추가하기 + * - 맵에 존재하면 현재 인덱스와, 해당 숫자의 인덱스 담아서 즉시 리턴하기 + * + * 시간복잡도 : O(n) + * - nums 배열 길이만큼 1회 순회하니까 O(n) + * - 맵 조회 및 삽입은 O(1) + * + * 공간복잡도 : O(n) + * - 맵에 배열의 값 저장하니까 O(n) + * + * 엣지 케이스 : + * - 동일한 숫자가 있는 경우 : [3, 3], 6 => [0,1] + */ + +function twoSum(nums: number[], target: number): number[] { + const map = new Map(); + + for (let i = 0; i < nums.length; i++) { + const neededValue = target - nums[i]; + + if (map.has(neededValue)) { + return [map.get(neededValue)!, i]; + } + + map.set(nums[i], i); + } +} From 63043b76d232910f936ec6386f55472f9c636678 Mon Sep 17 00:00:00 2001 From: changchanghwang Date: Mon, 23 Dec 2024 12:17:32 +0900 Subject: [PATCH 020/183] feat: twoSum --- two-sum/changchanghwang.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 two-sum/changchanghwang.go diff --git a/two-sum/changchanghwang.go b/two-sum/changchanghwang.go new file mode 100644 index 000000000..7a4abf675 --- /dev/null +++ b/two-sum/changchanghwang.go @@ -0,0 +1,15 @@ +// Time: O(n) +// Space: O(n) +func twoSum(nums []int, target int) []int { + m := make(map[int]int) + + // O(n) + for i, num := range nums { + // O(1) + if j, ok := m[target-num]; ok && j != i { // target = num2 + num1 -> num2 = target - num1 을 이용하여 두 수를 찾는다. + return []int{j, i} + } + m[num] = i // 없다면 현재 수를 키로 하여 인덱스를 저장한다. + } + return nil +} From a3f13cf3bc04475db32fbcae4a6fc25a83f0fab8 Mon Sep 17 00:00:00 2001 From: Nayeon Date: Mon, 23 Dec 2024 17:27:17 +0900 Subject: [PATCH 021/183] Add solution for "219. Two Sum" --- two-sum/KwonNayeon.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/two-sum/KwonNayeon.py b/two-sum/KwonNayeon.py index 8b1378917..209596b1a 100644 --- a/two-sum/KwonNayeon.py +++ b/two-sum/KwonNayeon.py @@ -1 +1,27 @@ +""" +Constraints: + - 2 <= nums.length <= 10^4 + - -10^9 <= nums[i] <= 10^9 + - -10^9 <= target <= 10^9 + - Only one valid answer exists. + + Time Complexity: O(n²) + - 중첩 반복문을 사용하기 때문 + - 첫 번째 반복문: n번 + - 각각에 대해 두 번째 반복문: n-1, n-2, ... 1번 + - 따라서 총 연산 횟수는 n * (n-1)/2로 O(n²) + + Space Complexity: O(1) + - 추가 공간을 사용하지 않음 + - result 리스트는 항상 크기가 2로 고정 +""" +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + result = [] + + for i in range(len(nums)): + for j in range(i+1, len(nums)): + if nums[j] == target - nums[i]: + return [i, j] + From 5a19363503a0b2640151d7d53e1493ee07f2404e Mon Sep 17 00:00:00 2001 From: eunhwa99 Date: Mon, 23 Dec 2024 19:47:52 +0900 Subject: [PATCH 022/183] combination sum --- combination-sum/eunhwa99.java | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 combination-sum/eunhwa99.java diff --git a/combination-sum/eunhwa99.java b/combination-sum/eunhwa99.java new file mode 100644 index 000000000..5d6561a6b --- /dev/null +++ b/combination-sum/eunhwa99.java @@ -0,0 +1,32 @@ +import java.util.ArrayList; +import java.util.List; + +// backtracking +// 시간복잡도: 각 배열 원소마다 target을 만드는 데에 기여를 할 수도 있고 안 할 수도 있음 -> O(2^(target)) +// 공간복잡도: O(k * t) (k는 가능한 조합의 수, t는 각 조합의 크기) + +class Solution { + public List> combinationSum(int[] candidates, int target) { + List> result = new ArrayList<>(); + backtrack(candidates, target, 0, new ArrayList<>(), result); + return result; + } + + private void backtrack(int[] candidates, int target, int start, List currentCombination, List> result) { + // 목표값에 도달하면 현재 조합을 결과에 추가 + if (target == 0) { + result.add(new ArrayList<>(currentCombination)); + return; + } + + // 후보 숫자들을 탐색 + for (int i = start; i < candidates.length; i++) { + if (candidates[i] > target) continue; // 목표값보다 큰 숫자는 넘어감 + + currentCombination.add(candidates[i]); // 현재 숫자를 선택 + // 현재 숫자를 다시 사용할 수 있기 때문에 i를 그대로 두고 재귀 호출 + backtrack(candidates, target - candidates[i], i, currentCombination, result); + currentCombination.remove(currentCombination.size() - 1); // 백트래킹: 마지막 숫자 제거 + } + } +} From dbb2fdb3341e9ac57f4cc6a9c334defb076af4ff Mon Sep 17 00:00:00 2001 From: Taewan Lim Date: Mon, 23 Dec 2024 20:16:53 +0900 Subject: [PATCH 023/183] relocate comments --- two-sum/taewanseoul.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/two-sum/taewanseoul.ts b/two-sum/taewanseoul.ts index 783225776..97674206c 100644 --- a/two-sum/taewanseoul.ts +++ b/two-sum/taewanseoul.ts @@ -6,6 +6,9 @@ * * https://leetcode.com/problems/two-sum/description/ */ + +// O(n) time +// O(n) space function twoSum(nums: number[], target: number): number[] { const map = new Map(); @@ -16,6 +19,3 @@ function twoSum(nums: number[], target: number): number[] { map.set(nums[i], i); } } - -// O(n) time -// O(n) space From 40b1c97d52828d72c40eedf07deb4964a2d6ca1e Mon Sep 17 00:00:00 2001 From: Youngjae Kim Date: Mon, 23 Dec 2024 21:53:38 +0900 Subject: [PATCH 024/183] add: solve #219 Two Sum with ts --- two-sum/Yjason-K.ts | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 two-sum/Yjason-K.ts diff --git a/two-sum/Yjason-K.ts b/two-sum/Yjason-K.ts new file mode 100644 index 000000000..daf78020b --- /dev/null +++ b/two-sum/Yjason-K.ts @@ -0,0 +1,25 @@ +/** + * 주어진 배열에서 두 숫자의 합이 target이 되는 idx 쌍을 반환하는 함수 + * - 시간 복잡도: O(n) + * - 한번의 배열을 순회하며 Map에 값을 저장하고, Map에서 값을 찾음 + * - 공간 복잡도: O(n) + * - 숫자와 그때의 idx를 쌍으로하는 Map + * + * @param {number[]} nums - 숫자 배열 + * @param {number} target - 타겟 합 + * @returns {number[]} - 합을 만들 수 있는 idx 배열 + */ +function twoSum(nums: number[], target: number): number[] { + const map = new Map(); + for (let i = 0; i < nums.length; i++) { + const cur = nums[i]; // 현재 값 + const reamin = target - cur; // 나머지 + if (map.has(reamin)) { + // Non-null assertion operator(!)를 사용하여 undefined가 아님을 단언 + return [map.get(reamin)!, i]; + } + // 나머지를 찾지 못한 경우 현재 값을 저장 + map.set(cur, i); + } + return []; // 목표 합을 만들 수 있는 숫자가 없는 경우 빈 배열 반환 +} From 904130c41e6e0571254a8290e66af12cfb57e8c5 Mon Sep 17 00:00:00 2001 From: Taewan Lim Date: Mon, 23 Dec 2024 22:06:22 +0900 Subject: [PATCH 025/183] reverse-bits --- reverse-bits/taewanseoul.ts | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 reverse-bits/taewanseoul.ts diff --git a/reverse-bits/taewanseoul.ts b/reverse-bits/taewanseoul.ts new file mode 100644 index 000000000..eb454e1d1 --- /dev/null +++ b/reverse-bits/taewanseoul.ts @@ -0,0 +1,26 @@ +/** + * 190. Reverse Bits + * Reverse bits of a given 32 bits unsigned integer. + * + * https://leetcode.com/problems/reverse-bits/description/ + */ + +// O(1) time +// O(1) space +function reverseBits(n: number): number { + const bits: number[] = []; + + while (bits.length < 32) { + bits.push(n & 1); + n = n >> 1; + } + + let result = 0; + let scale = 1; + for (let i = bits.length - 1; i >= 0; i--) { + result += bits[i] * scale; + scale *= 2; + } + + return result; +} From 0366d407ef5fcb5c918e7a8fa21ec6b1777fa733 Mon Sep 17 00:00:00 2001 From: jeehay Date: Mon, 23 Dec 2024 22:14:21 +0900 Subject: [PATCH 026/183] Add two-sum solution --- two-sum/Jeehay28.js | 49 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 two-sum/Jeehay28.js diff --git a/two-sum/Jeehay28.js b/two-sum/Jeehay28.js new file mode 100644 index 000000000..9b24e9073 --- /dev/null +++ b/two-sum/Jeehay28.js @@ -0,0 +1,49 @@ +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ + + +// Time Complexity : O(n) +// Space Complexity : O(n) + +var twoSum = function (nums, target) { + + let map = new Map(); + + for (let i = 0; i < nums.length; i++) { + + const temp = target - nums[i]; + + if (map.has(temp)) { + return [i, map.get(temp)] + } + + map.set(nums[i], i); + } + + return []; +} + + +// Time Complexity: O(n^2) +// Space Complexity: O(1) +// This solution is straightforward but inefficient for large arrays. For better performance, consider the hashmap approach. + +// var twoSum = function (nums, target) { + +// for (let i = 0; i < nums.length; i++) { + +// const loc = nums.indexOf((target - nums[i]), i + 1); + +// if (loc >= 0) { +// return [i, loc] +// } else { +// continue; +// } + +// } + +// }; + From 6e058a54ed79beab264fdf805256d8d775df95f5 Mon Sep 17 00:00:00 2001 From: Heejin Ham Date: Mon, 23 Dec 2024 22:21:00 +0900 Subject: [PATCH 027/183] [Week3](gmlwls96) Product of array except self --- product-of-array-except-self/gmlwls96.kt | 20 ++++++++++++++++++++ two-sum/gmlwls96.kt | 2 +- 2 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 product-of-array-except-self/gmlwls96.kt diff --git a/product-of-array-except-self/gmlwls96.kt b/product-of-array-except-self/gmlwls96.kt new file mode 100644 index 000000000..21c2f227c --- /dev/null +++ b/product-of-array-except-self/gmlwls96.kt @@ -0,0 +1,20 @@ +class Solution { + // 시간 : O(2n) = O(n) ,공간 : O(1) + fun productExceptSelf(nums: IntArray): IntArray { + val answer = IntArray(nums.size) { 1 } + + var n = 1 + for (i in 0 until nums.lastIndex) { + n *= nums[i] + answer[i + 1] = n + } + println(answer.toList()) + + n = 1 + for (i in nums.lastIndex downTo 1) { + n *= nums[i] + answer[i - 1] *= n + } + return answer + } +} diff --git a/two-sum/gmlwls96.kt b/two-sum/gmlwls96.kt index 5d7091c50..27b6dd147 100644 --- a/two-sum/gmlwls96.kt +++ b/two-sum/gmlwls96.kt @@ -1,5 +1,5 @@ class Solution { - // 시간 : O(logN), 공간(2N) + // 시간 : O(NlogN)-정렬하는데 드는 시간복잡도., 공간(2N) fun twoSum(nums: IntArray, target: Int): IntArray { val sortNums = List(nums.size) { listOf(nums[it], it) }.sortedBy { it[0] } // 1. list( list('값', 'index')) 형태의 list를 만들고 값을 기준으로 정렬한다. From a6b54a4406e3600ba5a3d5710addb4ed94b4f8e0 Mon Sep 17 00:00:00 2001 From: eunhwa99 Date: Mon, 23 Dec 2024 22:21:38 +0900 Subject: [PATCH 028/183] maximum subarray --- maximum-subarray/eunhwa99.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 maximum-subarray/eunhwa99.java diff --git a/maximum-subarray/eunhwa99.java b/maximum-subarray/eunhwa99.java new file mode 100644 index 000000000..0383bfbdc --- /dev/null +++ b/maximum-subarray/eunhwa99.java @@ -0,0 +1,15 @@ +// 시간 복잡도: DP -> O(N) +// 공간 복잡도: nums 배열 크기 - O(N) + +class Solution { + public int maxSubArray(int[] nums) { + int currentSum = nums[0]; + int maxSum = currentSum; + for (int i = 1; i < nums.length; ++i) { + currentSum = Math.max(currentSum + nums[i], nums[i]); + maxSum = Math.max(maxSum, currentSum); + } + + return maxSum; + } +} From ab85227a70e46f1f72cb0ebff5c09a56cb3b2bd0 Mon Sep 17 00:00:00 2001 From: Dusuna <94776135+dusunax@users.noreply.github.com> Date: Mon, 23 Dec 2024 22:25:10 +0900 Subject: [PATCH 029/183] add solution: two-sum --- two-sum/dusunax.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 two-sum/dusunax.py diff --git a/two-sum/dusunax.py b/two-sum/dusunax.py new file mode 100644 index 000000000..fa188e8d9 --- /dev/null +++ b/two-sum/dusunax.py @@ -0,0 +1,33 @@ +''' +# 1. Two Sum + +use a hash map to store the numbers and their indices. +iterate through the list and check if the complement of the current number (target - nums[i]) is in the hash map. + +(assume that each input would have exactly one solution) +- if it is a pairNum, return the indices of the two numbers. +- if it is not, add the current number and its index to the hash map. + + +## Time and Space Complexity + +``` +TC: O(n) +SC: O(n) +``` + +#### TC is O(n): +- iterating through the list just once to find the two numbers. = O(n) + +#### SC is O(n): +- using a hash map to store the numbers and their indices. = O(n) +''' + +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + map = {} + for i in range(len(nums)): + pairNum = target - nums[i] + if pairNum in map: + return [map.get(pairNum), i] + map[nums[i]] = i \ No newline at end of file From 8c1043eb8eef5caf4a093ae7d63dba24a20add28 Mon Sep 17 00:00:00 2001 From: Dusuna <94776135+dusunax@users.noreply.github.com> Date: Tue, 24 Dec 2024 01:10:46 +0900 Subject: [PATCH 030/183] fix: add line breaks --- two-sum/dusunax.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/two-sum/dusunax.py b/two-sum/dusunax.py index fa188e8d9..2377329c2 100644 --- a/two-sum/dusunax.py +++ b/two-sum/dusunax.py @@ -30,4 +30,4 @@ def twoSum(self, nums: List[int], target: int) -> List[int]: pairNum = target - nums[i] if pairNum in map: return [map.get(pairNum), i] - map[nums[i]] = i \ No newline at end of file + map[nums[i]] = i From 89cf4e9153361630f90dd09b62731e2156c5626f Mon Sep 17 00:00:00 2001 From: easyone Date: Tue, 24 Dec 2024 08:21:09 +0900 Subject: [PATCH 031/183] Feat: Add solution of two-sum. --- two-sum/easyone-jwlee.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 two-sum/easyone-jwlee.go diff --git a/two-sum/easyone-jwlee.go b/two-sum/easyone-jwlee.go new file mode 100644 index 000000000..42d736d64 --- /dev/null +++ b/two-sum/easyone-jwlee.go @@ -0,0 +1,20 @@ +// 풀이 +// map의 key에 값, value에 index를 넣어, target-num이 map에 존재할 때를 찾기. +// 오직 하나의 답만 무조건 존재한다고 했기 때문에 찾자마자 return. + +// TC +// 가장 마지막 인덱스까지 가서야 값을 구할 수 있었다고 하면, nums의 길이만큼 for문을 한바퀴 돌기때문에 O(n). + +// SC +// 중복없이 마지막 인덱스까지 가서 값을 구한다면 들어오는 nums의 길이만큼 map도 공간을 차지하게 되므로 O(n). + +func twoSum(nums []int, target int) []int { + m := make(map[int]int) + for i, num := range nums { + if index, ok := m[target-num]; ok { + return []int{index, i} + } + m[num] = i + } + return []int{0, 0} +} From b57c526f2a9a278d066f414b1a0d66e8e5bf6378 Mon Sep 17 00:00:00 2001 From: Jaehyeon Robert Han Date: Mon, 23 Dec 2024 16:53:15 -0800 Subject: [PATCH 032/183] two-sum solution --- two-sum/Zioq.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 two-sum/Zioq.js diff --git a/two-sum/Zioq.js b/two-sum/Zioq.js new file mode 100644 index 000000000..592da9b53 --- /dev/null +++ b/two-sum/Zioq.js @@ -0,0 +1,30 @@ +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var twoSum = function(nums, target) { + // Initialize object to save remained value with index + let remain_with_index_obj = {} + + for ( let i =0; i Date: Tue, 24 Dec 2024 14:57:45 +0900 Subject: [PATCH 033/183] feat : combination-sum --- combination-sum/ekgns33.java | 42 ++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 combination-sum/ekgns33.java diff --git a/combination-sum/ekgns33.java b/combination-sum/ekgns33.java new file mode 100644 index 000000000..2288d70e8 --- /dev/null +++ b/combination-sum/ekgns33.java @@ -0,0 +1,42 @@ +import java.util.ArrayList; +import java.util.List; + +/** + input : array of distinct integers, single integer target + output : all unique combinations of candidates where chosen ones sum is target + constraints: + 1) can we use same integer multiple times? + yes + 2) input array can be empty? + no. [1, 30] + + + solution 1) + combination >> back-tracking + O(2^n) at most 2^30 << (2^10)^3 ~= 10^9 + + tc : O(2^n) sc : O(n) call stack + */ +class Solution { + public List> combinationSum(int[] candidates, int target) { + List> answer = new ArrayList<>(); + List prev = new ArrayList<>(); + backTrackingHelper(answer, prev, candidates, target, 0, 0); + return answer; + } + private void backTrackingHelper(List> ans, List prev, int[] cands, int target, int curSum, int p) { + if(curSum == target) { + ans.add(new ArrayList(prev)); + return; + } + if(p >= cands.length) return; + + for(int i = p; i< cands.length; i++) { + if((curSum + cands[i]) <= target) { + prev.add(cands[i]); + backTrackingHelper(ans, prev, cands, target, curSum + cands[i],i); + prev.remove(prev.size() - 1); + } + } + } +} \ No newline at end of file From 98dfafb3ead29673a2c1fb7e63dea7cc64ac279c Mon Sep 17 00:00:00 2001 From: ekgns33 Date: Tue, 24 Dec 2024 14:58:12 +0900 Subject: [PATCH 034/183] feat : product-of-arrray-except-self --- product-of-array-except-self/ekgns33.java | 72 +++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 product-of-array-except-self/ekgns33.java diff --git a/product-of-array-except-self/ekgns33.java b/product-of-array-except-self/ekgns33.java new file mode 100644 index 000000000..b53937cd3 --- /dev/null +++ b/product-of-array-except-self/ekgns33.java @@ -0,0 +1,72 @@ +/* +input : array of integer +output : array of integer that each element + is product of all the elements except itself +constraint +1) is the result of product also in range of integer? +yes product of nums is guaranteed to fit 32-bit int +2) how about zero? +doesn't matter if the prduct result is zero +3) is input array non-empty? +yes. length of array is in range [2, 10^5] + +solution1) brute force + +calc all the product except current index element + +tc : O(n^2) sc : O(n) << for the result. when n is the length of input array + +solution 2) better? +ds : array +algo : hmmm we can reuse the product using prefix sum + +1) get prefix sum from left to right and vice versa : 2-O(n) loop + 2-O(n) space +2) for i = 0 to n-1 when n is the length of input + get product of leftPrfex[i-1] * rightPrefix[i+1] + // edge : i == 0, i == n-1 + +tc : O(n) sc : O(n) + +solution 3) optimal? +can we reduce space? +1) product of all elements. divide by current element. + + > edge : what if current element is zero? + 2) if there exists only one zero: + all the elements except zero index will be zero + 3) if there exist multiple zeros: + all the elements are zero + 4) if there is no zero + do 1) + */ +class Solution { + public int[] productExceptSelf(int[] nums) { + int n = nums.length, product = 1, zeroCount = 0; + for(int num : nums) { + if(num == 0) { + zeroCount ++; + if(zeroCount > 1) break; + } else { + product *= num; + } + } + + int[] answer = new int[n]; + if(zeroCount > 1) { + return answer; + } else if (zeroCount == 1) { + for(int i = 0; i < n; i++) { + if(nums[i] != 0) { + answer[i] = 0; + continue; + } + answer[i] = product; + } + } else { + for(int i = 0; i < n; i++) { + answer[i] = product / nums[i]; + } + } + return answer; + } +} \ No newline at end of file From 22b7af4b121725c0b7df0fcd25364d6f61050d27 Mon Sep 17 00:00:00 2001 From: ekgns33 Date: Tue, 24 Dec 2024 14:58:28 +0900 Subject: [PATCH 035/183] feat : reverse-bits --- reverse-bits/ekgns33.java | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 reverse-bits/ekgns33.java diff --git a/reverse-bits/ekgns33.java b/reverse-bits/ekgns33.java new file mode 100644 index 000000000..b78c5b73e --- /dev/null +++ b/reverse-bits/ekgns33.java @@ -0,0 +1,39 @@ +/* +input : 32 bit unsigned integer n +output : unsigned integer representation of reversed bit +constraint : +1) input is always 32 bit unsigned integer +2) implementation should not be affected by programming language + +solution 1) + +get unsigned integer bit representation + +build string s O(n) +reverse O(n) +get integer O(n) + +tc : O(n) sc : O(n) + +solution 2) one loop + +nth bit indicates (1< Date: Tue, 24 Dec 2024 14:58:36 +0900 Subject: [PATCH 036/183] feat : two-sum --- two-sum/ekgns33.java | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 two-sum/ekgns33.java diff --git a/two-sum/ekgns33.java b/two-sum/ekgns33.java new file mode 100644 index 000000000..097903bb7 --- /dev/null +++ b/two-sum/ekgns33.java @@ -0,0 +1,39 @@ +import java.util.HashMap; +import java.util.Map; + +/* +input : array of integers, single integer target +output : indices of the two numbers that they add up to target +constraint: +1) is integer positive? +no [-10^9, 10^9] +2) is there any duplicates? +yes. but only one valid answer exists +3) can i reuse elem? +no + +sol1) brute force +nested for loop. tc: O(n^2), sc: O(1) when n is the length of input + +sol2) better solution with hash map +iterate through the array + check if target - current elem exists + if return pair of indices + else save current elem and continue + +tc : O(n), sc: O(n) when n is the length of input + + */ +class Solution { + public int[] twoSum(int[] nums, int target) { + Map prev = new HashMap<>(); + for(int i = 0; i < nums.length; i++) { + int key = target - nums[i]; + if(prev.containsKey(key)) { + return new int[] {prev.get(key), i}; + } + prev.put(nums[i], i); + } + return null; + } +} From 27ea13d63b20750d9c9216e6577844658a4068b6 Mon Sep 17 00:00:00 2001 From: ekgns33 Date: Tue, 24 Dec 2024 15:00:25 +0900 Subject: [PATCH 037/183] fix : add empty line --- combination-sum/ekgns33.java | 2 +- product-of-array-except-self/ekgns33.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/combination-sum/ekgns33.java b/combination-sum/ekgns33.java index 2288d70e8..1e037722b 100644 --- a/combination-sum/ekgns33.java +++ b/combination-sum/ekgns33.java @@ -39,4 +39,4 @@ private void backTrackingHelper(List> ans, List prev, int } } } -} \ No newline at end of file +} diff --git a/product-of-array-except-self/ekgns33.java b/product-of-array-except-self/ekgns33.java index b53937cd3..14e313f2a 100644 --- a/product-of-array-except-self/ekgns33.java +++ b/product-of-array-except-self/ekgns33.java @@ -69,4 +69,4 @@ public int[] productExceptSelf(int[] nums) { } return answer; } -} \ No newline at end of file +} From e990fe7c01e9472e0b3897fde829359c74f0f10b Mon Sep 17 00:00:00 2001 From: gmlwls96 Date: Tue, 24 Dec 2024 16:27:40 +0900 Subject: [PATCH 038/183] [Week3](gmlwls96) Combination Sum --- combination-sum/gmlwls96.kt | 50 +++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 combination-sum/gmlwls96.kt diff --git a/combination-sum/gmlwls96.kt b/combination-sum/gmlwls96.kt new file mode 100644 index 000000000..c923dc8fe --- /dev/null +++ b/combination-sum/gmlwls96.kt @@ -0,0 +1,50 @@ +class Solution { + // 시간 : O(c^t), 공간 : O(t) + // 알고리즘 : dfs + val answerList = mutableSetOf>() + + fun combinationSum(candidates: IntArray, target: Int): List> { + candidates.sort() + combination( + candidates = candidates, + target = target, + current = 0, + currentList = listOf() + ) + return answerList.toList() + } + + private fun combination( + candidates: IntArray, + target: Int, + current: Int, + currentList: List + ) { + candidates.forEach { // candidates를 한개씩 꺼내 + val sum = current + it // 현재값을 더했을때 + when { + sum == target -> { // sum이 target과 동일한 값이면 answer 에 추가. + answerList.add( + currentList.toMutableList().apply { + add(it) + sort() + } + ) + } + + sum < target -> { // sum이 모자르면 다른 조합을 찾기 위해 재귀 호출. + combination( + candidates = candidates, + target = target, + current = sum, + currentList = currentList.toMutableList().apply { + add(it) + } + ) + } + + else -> return + } + } + } +} From 320cd1c836a99e338c03a6f6673626b1eb779696 Mon Sep 17 00:00:00 2001 From: chae Date: Tue, 24 Dec 2024 17:26:49 +0900 Subject: [PATCH 039/183] feat: two-sum solution --- two-sum/YeomChaeeun.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 two-sum/YeomChaeeun.ts diff --git a/two-sum/YeomChaeeun.ts b/two-sum/YeomChaeeun.ts new file mode 100644 index 000000000..977134d44 --- /dev/null +++ b/two-sum/YeomChaeeun.ts @@ -0,0 +1,20 @@ +/** + * 배열 두 수의 합이 target 과 같은 값 + * 알고리즘 복잡도: + * - 시간복잡도: O(n^2) + * - 공간복잡도: O(1) + * @param nums + * @param target + */ +function twoSum(nums: number[], target: number): number[] { + let result: number[] = []; + + for(let i = 0; i < nums.length; i++) { + for(let j = i + 1; j < nums.length; j++) { + if(nums[i] + nums[j] === target) { + result.push(i, j); + return result; + } + } + } +} From 39fc7a91ba8bf98efce9522592f7a2f586993ad6 Mon Sep 17 00:00:00 2001 From: Dal_Peng Date: Tue, 24 Dec 2024 20:57:58 +0900 Subject: [PATCH 040/183] :art: TwoSum Solution --- two-sum/dalpang81.java | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 two-sum/dalpang81.java diff --git a/two-sum/dalpang81.java b/two-sum/dalpang81.java new file mode 100644 index 000000000..40d85ff1b --- /dev/null +++ b/two-sum/dalpang81.java @@ -0,0 +1,23 @@ +/* +* 시간복잡도 : O(n) +* 공간복잡도 : O(n) +* */ + +import java.util.HashMap; +import java.util.Map; + +class Solution { + public int[] twoSum(int[] nums, int target) { + Map map = new HashMap<>(); + + for (int i = 0; i < nums.length; i++) { + int complement = target - nums[i]; + + if (map.containsKey(complement)) { + return new int[] { map.get(complement), i }; + } + map.put(nums[i], i); + } + return null; + } +} \ No newline at end of file From 5fb75d02f3c44a13a5a3a5c72b55fb3ab74b5831 Mon Sep 17 00:00:00 2001 From: Dal_Peng Date: Tue, 24 Dec 2024 21:01:20 +0900 Subject: [PATCH 041/183] :bug: add EndLine --- two-sum/bky373.java | 1 + 1 file changed, 1 insertion(+) diff --git a/two-sum/bky373.java b/two-sum/bky373.java index e6e1a2d85..ce2f53bc5 100644 --- a/two-sum/bky373.java +++ b/two-sum/bky373.java @@ -20,3 +20,4 @@ public int[] twoSum(int[] nums, int target) { return new int[]{}; } } + From 6f3bc6d69aba8eb72cbb5e26afbceb3dd32f7bf7 Mon Sep 17 00:00:00 2001 From: Dal_Peng Date: Tue, 24 Dec 2024 21:02:06 +0900 Subject: [PATCH 042/183] Revert ":bug: add EndLine" This reverts commit 5fb75d02f3c44a13a5a3a5c72b55fb3ab74b5831. --- two-sum/bky373.java | 1 - 1 file changed, 1 deletion(-) diff --git a/two-sum/bky373.java b/two-sum/bky373.java index ce2f53bc5..e6e1a2d85 100644 --- a/two-sum/bky373.java +++ b/two-sum/bky373.java @@ -20,4 +20,3 @@ public int[] twoSum(int[] nums, int target) { return new int[]{}; } } - From 2d97feaaf65b23ff44729f1d1df321b18cc136b7 Mon Sep 17 00:00:00 2001 From: Dal_Peng Date: Tue, 24 Dec 2024 21:02:24 +0900 Subject: [PATCH 043/183] :bug: add EndLine --- two-sum/dalpang81.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/two-sum/dalpang81.java b/two-sum/dalpang81.java index 40d85ff1b..1742ee8af 100644 --- a/two-sum/dalpang81.java +++ b/two-sum/dalpang81.java @@ -20,4 +20,4 @@ public int[] twoSum(int[] nums, int target) { } return null; } -} \ No newline at end of file +} From 306fe90bcc8087f951a8dd48d9a46528ae92eb98 Mon Sep 17 00:00:00 2001 From: Taewan Lim Date: Tue, 24 Dec 2024 23:26:11 +0900 Subject: [PATCH 044/183] product-of-array-except-self --- product-of-array-except-self/taewanseoul.ts | 28 +++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 product-of-array-except-self/taewanseoul.ts diff --git a/product-of-array-except-self/taewanseoul.ts b/product-of-array-except-self/taewanseoul.ts new file mode 100644 index 000000000..8aba4f739 --- /dev/null +++ b/product-of-array-except-self/taewanseoul.ts @@ -0,0 +1,28 @@ +/** + * 238. Product of Array Except Self + * Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. + * The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. + * You must write an algorithm that runs in O(n) time and without using the division operation. + * + * https://leetcode.com/problems/product-of-array-except-self/description/ + */ + +// O(n) time +// O(1) space +function productExceptSelf(nums: number[]): number[] { + const result = new Array(nums.length).fill(1); + + let left = 1; + for (let i = 0; i < nums.length - 1; i++) { + left *= nums[i]; + result[i + 1] *= left; + } + + let right = 1; + for (let i = nums.length - 1; i > 0; i--) { + right *= nums[i]; + result[i - 1] *= right; + } + + return result; +} From cffced5ac6090a12dc2d6f2247a73961975a9c87 Mon Sep 17 00:00:00 2001 From: limlim Date: Tue, 24 Dec 2024 23:33:23 +0900 Subject: [PATCH 045/183] two sum solution --- two-sum/limlimjo.js | 55 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 two-sum/limlimjo.js diff --git a/two-sum/limlimjo.js b/two-sum/limlimjo.js new file mode 100644 index 000000000..eade7cf51 --- /dev/null +++ b/two-sum/limlimjo.js @@ -0,0 +1,55 @@ +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var twoSum = function (nums, target) { + for (let i = 0; i < nums.length; i++) { + for (let j = 0; j < nums.length; j++) { + if (i !== j) { + if (nums[i] + nums[j] === target) { + return [i, j]; + } + } + } + } +}; + +// 처음에 풀었던 방법 -> 시간 복잡도가 O(n^2)로 nums 배열에 있는 값이 늘어날수록 성능상 좋지 못함 +// 시간 복잡도: O(n^2) +// 공간 복잡도: O(1) + +// 두 번째 푼 방법 -> 이전에 threeSum 문제 풀 때 정렬 + 포인터 이용한 것처럼 이 문제도 그런식으로 품 +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var twoSum = function (nums, target) { + const numsIndex = nums.map((num, i) => ({ num, i })); // 원래 인덱스 저장 + //console.log(numsIndex); + + numsIndex.sort((a, b) => a.num - b.num); // 오름차순 정렬 + //console.log(numsIndex); + + // left와 right 포인터 이용해 target값과 동일한 것 찾기 + let left = 0; + let right = numsIndex.length - 1; + + while (left < right) { + const sum = numsIndex[left].num + numsIndex[right].num; + + if (sum > target) { + right--; + } else if (sum < target) { + left++; + } else { + return [numsIndex[left].i, numsIndex[right].i]; + } + } + return null; +}; + +// 첫 번째 푼 방법보다 공간 복잡도가 늘어났지만 시간 복잡도는 줄어듦 +// 시간 복잡도: O(n log n) +// 공간 복잡도: O(n) From 2cb29dcda9eab1bc93dfaaa2a490cbdba4762276 Mon Sep 17 00:00:00 2001 From: smg0725 Date: Tue, 24 Dec 2024 23:44:55 +0900 Subject: [PATCH 046/183] paragon0107 two-sum --- leetcode-study.iml | 82 ++++++++++++++++++++++++++++++++++++++++ two-sum/paragon0107.java | 21 ++++++++++ 2 files changed, 103 insertions(+) create mode 100644 leetcode-study.iml create mode 100644 two-sum/paragon0107.java diff --git a/leetcode-study.iml b/leetcode-study.iml new file mode 100644 index 000000000..0184c1642 --- /dev/null +++ b/leetcode-study.iml @@ -0,0 +1,82 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/two-sum/paragon0107.java b/two-sum/paragon0107.java new file mode 100644 index 000000000..ec68694ac --- /dev/null +++ b/two-sum/paragon0107.java @@ -0,0 +1,21 @@ + +import java.util.HashMap; +import java.util.Map; + +class Solution { + public int[] twoSum(int[] nums, int target) { + Map map = new HashMap<>(); + for(int i =0;i Date: Tue, 24 Dec 2024 23:48:07 +0900 Subject: [PATCH 047/183] paragon0107 two-sum --- two-sum/paragon0107.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/two-sum/paragon0107.java b/two-sum/paragon0107.java index ec68694ac..01da0e33c 100644 --- a/two-sum/paragon0107.java +++ b/two-sum/paragon0107.java @@ -18,4 +18,4 @@ public int[] twoSum(int[] nums, int target) { } return null; } -} \ No newline at end of file +} From cd70330ea1783a7c06ff370070698707a7c59221 Mon Sep 17 00:00:00 2001 From: thispath98 Date: Tue, 24 Dec 2024 23:58:40 +0900 Subject: [PATCH 048/183] feat: Add reverse-bits solutions --- reverse-bits/thispath98.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 reverse-bits/thispath98.py diff --git a/reverse-bits/thispath98.py b/reverse-bits/thispath98.py new file mode 100644 index 000000000..38be2e89a --- /dev/null +++ b/reverse-bits/thispath98.py @@ -0,0 +1,26 @@ +class Solution: + def reverseBits(self, n: int) -> int: + """ + Intuition: + 비트를 역순으로 순회한다. + answer에는 최대값(2^31)부터 최소값(2^0)으로 감소하는 + 방식으로 업데이트한다. + + Time Complexity: + O(N): + n을 1번 순회하며 답을 찾으므로, + O(N)의 시간복잡도가 소요된다. + + Space Complexity: + O(1): + answer에 값을 업데이트 하므로, 상수의 + 공간복잡도가 소요된다. + + Key takeaway: + 숫자를 binary string으로 만드는 bin() 메소드를 + 알게 되었다. + """ + answer = 0 + for i, bit in enumerate(bin(n)[2:][::-1]): + answer += int(bit) * 2 ** (31 - i) + return answer From 3e3a08e5e2e16302ec1887543075b9617f9488a3 Mon Sep 17 00:00:00 2001 From: thispath98 Date: Tue, 24 Dec 2024 23:58:50 +0900 Subject: [PATCH 049/183] feat: Add two-sum solutions --- two-sum/thispath98.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 two-sum/thispath98.py diff --git a/two-sum/thispath98.py b/two-sum/thispath98.py new file mode 100644 index 000000000..cca31e787 --- /dev/null +++ b/two-sum/thispath98.py @@ -0,0 +1,23 @@ +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + """ + Intuition: + 기존에 풀었던 3sum 문제와 유사하게, + 해시에 현재 숫자와 더해서 target이 되는 값을 찾는다. + 만약 없을 경우, 해시에 현재 값과 인덱스를 저장한다. + + Time Complexity: + O(N): + 해시는 접근하는 데에 O(1)이 소요되고, + 총 N번 반복해야 하므로 시간복잡도는 O(N)이다. + + Space Complexity: + O(N): + 최악의 경우 해시에 N개의 숫자와 인덱스를 저장해야 한다. + """ + complement_dict = {} + for i, num in enumerate(nums): + if target - num in complement_dict: + return [complement_dict[target - num], i] + else: + complement_dict[num] = i From da5c5c655dfd4d28327482bf918379cbfbe3c26f Mon Sep 17 00:00:00 2001 From: Jaehyeon Robert Han Date: Tue, 24 Dec 2024 14:18:41 -0800 Subject: [PATCH 050/183] reverse-bit solution --- reverse-bits/Zioq.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 reverse-bits/Zioq.js diff --git a/reverse-bits/Zioq.js b/reverse-bits/Zioq.js new file mode 100644 index 000000000..20f3d5ae6 --- /dev/null +++ b/reverse-bits/Zioq.js @@ -0,0 +1,19 @@ +/** + * @param {number} n - a positive integer + * @return {number} - a positive integer + */ +var reverseBits = function(n) { + let result = 0; //Initial value + for (let i=0; i < 32; i++) { //The loop iterates 32 times, as the input n is a 32-bit unsigned integer + result = (result << 1) | (n & 1); // Shift the result to the left by 1 bit OR it with the least significant bit of n. + n >>= 1; // Shifts the bits of n one place to the right, effectively "removing" the processed LSB. + } + return result >>> 0; +}; +/* + Time Complexity: O(1), because we always loop exactly 32 times, regardless of the input. + Space Complexity: O(1), because we use a constant amount of space. +*/ + + + From 579021bc75050e36b53a383185c50255e77fba51 Mon Sep 17 00:00:00 2001 From: GangBean Date: Wed, 25 Dec 2024 07:51:13 +0900 Subject: [PATCH 051/183] feat: solve reverse bits --- reverse-bits/GangBean.java | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 reverse-bits/GangBean.java diff --git a/reverse-bits/GangBean.java b/reverse-bits/GangBean.java new file mode 100644 index 000000000..93f7ad6c1 --- /dev/null +++ b/reverse-bits/GangBean.java @@ -0,0 +1,24 @@ +public class Solution { + // you need treat n as an unsigned value + public int reverseBits(int n) { + /** + 1. understanding + - return the reversed 32 bit input num + 2. strategy + - assign stack + - iterate until stack.size is 32 + - push value % 2, and value /= 2 + 3. complexity + - time: O(1) + - space: O(1) + */ + int reversed = 0; + for (int i = 0; i < 32; i++) { + reversed <<= 1; + reversed |= n & 1; + n >>= 1; + } + return reversed; + } +} + From 4c6e48ba6ce2d280a6c79a5f22a1dd168697d6d2 Mon Sep 17 00:00:00 2001 From: GangBean Date: Wed, 25 Dec 2024 08:45:43 +0900 Subject: [PATCH 052/183] feat: solve product of array except self --- product-of-array-except-self/GangBean.java | 56 ++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 product-of-array-except-self/GangBean.java diff --git a/product-of-array-except-self/GangBean.java b/product-of-array-except-self/GangBean.java new file mode 100644 index 000000000..cf53f48c1 --- /dev/null +++ b/product-of-array-except-self/GangBean.java @@ -0,0 +1,56 @@ +class Solution { + public int[] productExceptSelf(int[] nums) { + /** + 1. understanding + - given integer array nums + - product of which's all elements except that element + - should be under O(N) time complexity + - should not use division operation + 2. strategy + - brute force: O(n^2) + - for every elements, calculate product of other elements + - 1: 2 * [3 * 4] + - 2: 1 * [3 * 4] + - 3: [1 * 2] * 4 + - 4: [1 * 2] * 3 + - dynamic programming + - assign array mem to memorize product till that idx + - mem memorize in ascending order product value and reverse order product value + 3. complexity + - time: O(N) + - space: O(N) + */ + // 1. assign array variable mem + int[][] mem = new int[nums.length][]; + for (int i = 0 ; i < nums.length; i++) { + mem[i] = new int[2]; + } + + // 2. calculate product values + for (int i = 0 ; i < nums.length; i++) { // O(N) + if (i == 0) { + mem[i][0] = nums[i]; + continue; + } + mem[i][0] = nums[i] * mem[i-1][0]; + } + + for (int i = nums.length - 1; i >= 0; i--) { // O(N) + if (i == nums.length - 1) { + mem[i][1] = nums[i]; + continue; + } + mem[i][1] = nums[i] * mem[i+1][1]; + } + + int[] ret = new int[nums.length]; + for (int i = 0; i < nums.length; i++) { // O(N) + int left = (i - 1) >= 0 ? mem[i-1][0] : 1; + int right = (i + 1) < nums.length ? mem[i+1][1] : 1; + ret[i] = left * right; + } + + return ret; + } +} + From 0c544ebb3d9e3b0dd34b642b1898cc39925b5d9e Mon Sep 17 00:00:00 2001 From: GangBean Date: Wed, 25 Dec 2024 09:45:56 +0900 Subject: [PATCH 053/183] feat: solve maximum subarray --- maximum-subarray/GangBean.java | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 maximum-subarray/GangBean.java diff --git a/maximum-subarray/GangBean.java b/maximum-subarray/GangBean.java new file mode 100644 index 000000000..1eebca0ab --- /dev/null +++ b/maximum-subarray/GangBean.java @@ -0,0 +1,28 @@ +class Solution { + public int maxSubArray(int[] nums) { + /** + 1. understanding + - integer array nums + - find largest subarray sum + 2. starategy + - calculate cumulative sum + - mem[i+1] = num[i+1] + mem[i] if (num[i+1] + mem[i] >= 0) else num[i+1] + 3. complexity + - time: O(N) + - space: O(1) + */ + int prev = 0; + int curr = 0; + int max = Integer.MIN_VALUE; + for (int i = 0 ; i < nums.length; i++) { + curr = nums[i]; + if (prev >= 0) { + curr += prev; + } + max = Math.max(max, curr); + prev = curr; + } + return max; + } +} + From 64d6240f98551b1894faac184cb0d0a495239d9d Mon Sep 17 00:00:00 2001 From: bus710 Date: Tue, 24 Dec 2024 16:56:37 -0800 Subject: [PATCH 054/183] leetcode week3-1 --- two-sum/bus710.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 two-sum/bus710.go diff --git a/two-sum/bus710.go b/two-sum/bus710.go new file mode 100644 index 000000000..7542c9f1e --- /dev/null +++ b/two-sum/bus710.go @@ -0,0 +1,15 @@ +// O(n/2) as we only visit the half of the i*j + +package hello + +func twoSum(nums []int, target int) []int { + for i := range nums { + for j := i + 1; j < len(nums); j++ { + if (nums[i] + nums[j]) == target { + return []int{i, j} + } + } + } + + return nil +} From ba0ac0af779a50d5c0ca8e6f44f05c957566167b Mon Sep 17 00:00:00 2001 From: thispath98 Date: Wed, 25 Dec 2024 10:55:39 +0900 Subject: [PATCH 055/183] feat: Add product-of-array-except-self solutions --- product-of-array-except-self/thispath98.py | 35 ++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 product-of-array-except-self/thispath98.py diff --git a/product-of-array-except-self/thispath98.py b/product-of-array-except-self/thispath98.py new file mode 100644 index 000000000..c74d6616a --- /dev/null +++ b/product-of-array-except-self/thispath98.py @@ -0,0 +1,35 @@ +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + """ + Intuition: + i번째 인덱스의 값을 계산하기 위해서는 + 0 ~ i-1 까지의 값과 i+1 ~ N 까지의 값을 모두 곱해야 한다. + 이의 누적곱을 저장하여, 계산한다. + + Time Complexity: + O(N): + 리스트를 1번 순회하며 답을 찾으므로, + O(N)의 시간복잡도가 소요된다. + + Space Complexity: + O(N): + forward 배열과 backward 배열에 N개의 원소를 저장하므로 + O(N)의 공간복잡도가 소요된다. + + Key takeaway: + 스캔하여 값을 저장해두는 방식을 숙지하자. + """ + for_val = 1 + back_val = 1 + forward = [] + backward = [] + for i in range(len(nums)): + forward.append(for_val) + backward.append(back_val) + + for_val *= nums[i] + back_val *= nums[-(i + 1)] + backward = backward[::-1] + + answer = [forward[i] * backward[i] for i in range(len(nums))] + return answer From d2e6336c9989969711ce1679b338bbff9c52aaf3 Mon Sep 17 00:00:00 2001 From: limlim Date: Wed, 25 Dec 2024 11:39:05 +0900 Subject: [PATCH 056/183] reverse bits solution --- reverse-bits/limlimjo.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 reverse-bits/limlimjo.js diff --git a/reverse-bits/limlimjo.js b/reverse-bits/limlimjo.js new file mode 100644 index 000000000..d23ef8ba5 --- /dev/null +++ b/reverse-bits/limlimjo.js @@ -0,0 +1,29 @@ +/** + * @param {number} n - a positive integer + * @return {number} - a positive integer + */ +var reverseBits = function (n) { + // 문자열로 변환 + let nString = n.toString(2).padStart(32, "0"); + //console.log(nString); + + // 스택 생성 (스택은 나중에 들어온게 먼저 나가므로) + let stack = []; + + // nString 스택에 넣기 + for (let i = 0; i < nString.length; i++) { + stack.push(nString[i]); + } + + // pop하여 뒤집힌 문자열 만들기 + let reverseNString = ""; + for (let i = 0; i < nString.length; i++) { + reverseNString += stack.pop(); + } + + // 뒤집힌 문자열을 정수로 변환 + return parseInt(reverseNString, 2); +}; + +// 시간 복잡도: O(1) +// 공간 복잡도: O(1) From 1580f7193b1b644acabf6768e3f3e2517b3a0f54 Mon Sep 17 00:00:00 2001 From: Dusuna <94776135+dusunax@users.noreply.github.com> Date: Wed, 25 Dec 2024 20:03:52 +0900 Subject: [PATCH 057/183] add solution: reverse-bits --- reverse-bits/dusunax.py | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 reverse-bits/dusunax.py diff --git a/reverse-bits/dusunax.py b/reverse-bits/dusunax.py new file mode 100644 index 000000000..808d3efe4 --- /dev/null +++ b/reverse-bits/dusunax.py @@ -0,0 +1,41 @@ +''' +# 190. Reverse Bits + +SolutionA: using bin() and int() to convert the types. +SolutionB: using bitwise operations to reverse the bits. + +## Time and Space Complexity + +### SolutionA +``` +TC: O(32) -> O(1) +SC: O(1) +``` + +### SolutionB +``` +TC: O(32) -> O(1) +SC: O(1) +``` +''' +class Solution: + ''' + SolutionA + - using bin() and int() to convert the number to binary and back to integer. + - use .zfill(32) ensures that the binary string is always 32 bits long. + ''' + def reverseBitsA(self, n: int) -> int: + bit = bin(n)[2:].zfill(32) + return int(bit[::-1], 2) + + ''' + SolutionB + - using bitwise operations to reverse the bits. + - iterate through the bits and reverse them. + ''' + def reverseBitsB(self, n: int) -> int: + result = 0 + for i in range(32): + result = (result << 1) | (n & 1) # shift the result to the left & add LSB of n + n >>= 1 # shift n to the right & remove previous LSB + return result From a9d8a32c5027352910850d81936f2c36c080e819 Mon Sep 17 00:00:00 2001 From: chae Date: Wed, 25 Dec 2024 21:51:02 +0900 Subject: [PATCH 058/183] feat: reverse-bits solution --- reverse-bits/YeomChaeeun.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 reverse-bits/YeomChaeeun.ts diff --git a/reverse-bits/YeomChaeeun.ts b/reverse-bits/YeomChaeeun.ts new file mode 100644 index 000000000..70d7647ec --- /dev/null +++ b/reverse-bits/YeomChaeeun.ts @@ -0,0 +1,20 @@ +/** + * 정수를 비트로 변환후 뒤집어서 다시 정수로 반환 + * 알고리즘 복잡도 + * - 시간복잡도: O(1) + * - 공간복잡도: O(1) + * @param n + */ +function reverseBits(n: number): number { + // 2진수 배열로 변환 + let arr = n.toString(2).split('') + let len = arr.length + // 32비트 정렬 - 부족한 앞쪽에 0으로 채움 + for (let i = 0; i < (32 - len); i++) { + arr.unshift('0'); + } + // 뒤집은 후 합침 + let result = arr.reverse().join('') + // 2진수 정수로 변환하여 반환 + return parseInt(result,2) +} From 0a84ee7419d0bec8dafb4d827be7d6c57e44bc83 Mon Sep 17 00:00:00 2001 From: Seojung Noh <73627443+anniemon@users.noreply.github.com> Date: Wed, 25 Dec 2024 22:42:13 +0900 Subject: [PATCH 059/183] feat: two sum --- two-sum/anniemon.js | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 two-sum/anniemon.js diff --git a/two-sum/anniemon.js b/two-sum/anniemon.js new file mode 100644 index 000000000..403cefc67 --- /dev/null +++ b/two-sum/anniemon.js @@ -0,0 +1,20 @@ +/** + * 시간 복잡도: 최대 nums의 길이만큼 순회하므로, O(n) + * 공간 복잡도: map은 최대 nums의 길이 - 1 만큼의 공간을 차지하므로, O(n) + */ +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var twoSum = function(nums, target) { + const map = new Map(); + + for(let i = 0; i < nums.length; i++) { + const complement = target - nums[i]; + if(map.has(complement)) { + return [i, map.get(complement)] + } + map.set(nums[i], i); + } +}; From adc749af6d8676d5b72008a2df021831753a567f Mon Sep 17 00:00:00 2001 From: Seojung Noh <73627443+anniemon@users.noreply.github.com> Date: Thu, 26 Dec 2024 00:47:39 +0900 Subject: [PATCH 060/183] feat: reverse bits --- reverse-bits/anniemon.js | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 reverse-bits/anniemon.js diff --git a/reverse-bits/anniemon.js b/reverse-bits/anniemon.js new file mode 100644 index 000000000..e410af501 --- /dev/null +++ b/reverse-bits/anniemon.js @@ -0,0 +1,20 @@ +/** + * 시간 복잡도: 상수(32)번 반복이 일어나므로 O(1) + * 공간 복잡도: 상수(32) 크기의 배열을 생성하므로 O(1) + */ +/** + * @param {number} n - a positive integer + * @return {number} - a positive integer + */ +var reverseBits = function(n) { + let i = 0; + let arr = []; + while(i < 32) { + arr.push(n % 2); + n = Math.floor(n / 2); + i++; + } + const bi = arr.reverse().join(''); + const reversedBi = bi.split('').reverse().join(''); + return parseInt(reversedBi, 2); +}; From 205f7a97d3f7ce0e47f09b779de3c8fcb6604b4b Mon Sep 17 00:00:00 2001 From: Jaehyeon Robert Han Date: Wed, 25 Dec 2024 14:29:17 -0800 Subject: [PATCH 061/183] product-of-array-except-self solution --- product-of-array-except-self/Zioq.js | 36 ++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 product-of-array-except-self/Zioq.js diff --git a/product-of-array-except-self/Zioq.js b/product-of-array-except-self/Zioq.js new file mode 100644 index 000000000..ccb304bbd --- /dev/null +++ b/product-of-array-except-self/Zioq.js @@ -0,0 +1,36 @@ +/** + * @param {number[]} nums + * @return {number[]} + */ +var productExceptSelf = function(nums) { + let result = Array.from({length: nums.length}, () => 1) // Initialize return array + + // Iterate left to right + let left = 1; + for( let i =0 ; i=0; i-- ) { + result[i] *= right; + right *= nums[i]; + } + + // console.log(result) + return result +}; + +/* + Time Complexity: O(n): Loop the nth nums array length + Space Complexity: O(1) +*/ + + + +console.log(productExceptSelf([1,2,3,4])) +console.log(productExceptSelf([-1,1,0,-3,3])) + + From b2282f5330814439e9a41cc525cb5f65cbc5ad9a Mon Sep 17 00:00:00 2001 From: mmyeon Date: Thu, 26 Dec 2024 11:40:35 +0900 Subject: [PATCH 062/183] add solution : 238. Product of Array Except Self --- product-of-array-except-self/mmyeon.ts | 31 ++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 product-of-array-except-self/mmyeon.ts diff --git a/product-of-array-except-self/mmyeon.ts b/product-of-array-except-self/mmyeon.ts new file mode 100644 index 000000000..3e1bae2a3 --- /dev/null +++ b/product-of-array-except-self/mmyeon.ts @@ -0,0 +1,31 @@ +/** + * + * 접근 방법 : + * - O(n)으로 풀어야 하니까 중첩이 아닌 배열 개별로 2번 순회 방법으로 접근 + * - 왼쪽 곱(prefixProduct)과 오른쪽 곱((suffixProduct)을 따로 계산해서 결과값에 저장 + * + * 시간복잡도 : O(n) + * - 배열 길이만큼 순회하니까 O(n) + * + * 공간복잡도 : O(n) + * - 배열 길이만큼 결과값 저장하니까 O(n) + * + */ + +function productExceptSelf(nums: number[]): number[] { + let result: number[] = Array(nums.length).fill(1); + let prefixProduct = 1; + let suffixProduct = 1; + + for (let i = 0; i < nums.length; i++) { + result[i] = prefixProduct; + prefixProduct *= nums[i]; + } + + for (let i = nums.length - 1; i >= 0; i--) { + result[i] *= suffixProduct; + suffixProduct *= nums[i]; + } + + return result; +} From 1205cd033a1a963ecbb133ff7598fc132e1f8a3b Mon Sep 17 00:00:00 2001 From: thispath98 Date: Thu, 26 Dec 2024 12:36:30 +0900 Subject: [PATCH 063/183] feat: Add Combination Sum solutions --- combination-sum/thispath98.py | 41 +++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 combination-sum/thispath98.py diff --git a/combination-sum/thispath98.py b/combination-sum/thispath98.py new file mode 100644 index 000000000..8a1904c18 --- /dev/null +++ b/combination-sum/thispath98.py @@ -0,0 +1,41 @@ +class Solution: + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + """ + Intuition: + 리스트의 각 원소는 중복해서 사용할 수 있다. + 그렇다면 target은 재귀적으로 원소를 사용해서 + 모든 경우의 수를 탐색한다. + + Time Complexity: + O(N^2 log N): + 초기에 리스트의 원소를 정렬하는 데에 O(N log N)이 소요된다. + 또한, 재귀 함수는 최대 N번 호출될 수 있으며 + 각 재귀 함수에서는 정렬하여 세트에 추가하는 경우 + O(N log N)이 소요되고, + N개의 원소에 대해 for문을 반복한다. + 따라서 O(N^2 log N)의 시간복잡도가 소요된다. + + Space Complexity: + O(N): + 최악의 경우 answer set에 대략 N개의 tuple이 저장된다. + 따라서 O(N)의 공간복잡도가 소요된다. + """ + candidates.sort() # O(N log N) + answer_set = set() + + + def dfs(n, arr): + if n == 0: + answer_set.add(tuple(sorted(arr))) # O(N log N) + return + + for candidate in candidates: # O(N) + if n >= candidate: + arr.append(candidate) + dfs(n - candidate, arr) + arr.pop() + + + dfs(target, []) # O(N) + answer = list(answer_set) + return answer From 25f4d4cb2f7b2c5172badc7140c66e950265e223 Mon Sep 17 00:00:00 2001 From: thispath98 Date: Thu, 26 Dec 2024 12:40:25 +0900 Subject: [PATCH 064/183] feat: Add Maximum Subarray solutions --- maximum-subarray/thispath98.py | 37 ++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 maximum-subarray/thispath98.py diff --git a/maximum-subarray/thispath98.py b/maximum-subarray/thispath98.py new file mode 100644 index 000000000..1cae0041b --- /dev/null +++ b/maximum-subarray/thispath98.py @@ -0,0 +1,37 @@ +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + """ + Intuition: + 이전까지의 누적합에서 현재 원소를 추가할지 말지에 대한 + 결정을 매 iteration마다 반복한다. + 현재 원소를 추가했을 경우(누적합 + 현재 원소)와 + 현재 원소를 시작으로 하는 경우(현재 원소)를 비교하여 + dp 배열을 갱신한다. + + Time Complexity: + O(N): + 리스트를 1번 순회하며 답을 찾으므로, + O(N)의 시간복잡도가 소요된다. + + Space Complexity: + O(N): + dp 배열에 N개의 time step을 저장하므로 + O(N)의 공간복잡도가 소요된다. + + Key takeaway: + 초기에는 two pointer 방식을 생각했으나 + 해결을 하지 못해서 답안을 확인했다. + O(N)의 시간복잡도를 가지는 경우, DP도 풀이가 + 될 수 있음을 인지하자. + """ + dp = [0 for _ in nums] + dp[0] = nums[0] + for i in range(1, len(nums)): + cumsum = dp[i - 1] + nums[i] + cur = nums[i] + if cumsum > cur: + dp[i] = cumsum + else: + dp[i] = cur + + return max(dp) From 9f5f0a4f8c8bdd1b74476315e99d4650bfadac64 Mon Sep 17 00:00:00 2001 From: ekgns33 Date: Thu, 26 Dec 2024 12:47:56 +0900 Subject: [PATCH 065/183] feat : solve maximum-subarray --- maximum-subarray/ekgns33.java | 41 +++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 maximum-subarray/ekgns33.java diff --git a/maximum-subarray/ekgns33.java b/maximum-subarray/ekgns33.java new file mode 100644 index 000000000..f87957c53 --- /dev/null +++ b/maximum-subarray/ekgns33.java @@ -0,0 +1,41 @@ +/* +input : array of integer +output : largest sum of subarray +constraints : +1) is the input array not empty? +yes. at least one el +2) range of integers +[-10^4, 10^4] +3) maximum lenght of input +[10^5] +>> maximum sum = 10^5 * 10^4 = 10 ^ 9 < INTEGER + +sol1) brute force +nested for loop : O(n^2) +tc : O(n^2), sc : O(1) + +sol2) dp? +Subarray elements are continuous in the original array, so we can use dp. +let dp[i] represent the largest sum of a subarray where the ith element is the last element of the subarray. + +if dp[i-1] + curval < cur val : take curval +if dp[i-1] + cur val >= curval : take dp[i-1] + curval +tc : O(n) sc : O(n) + */ +class Solution { + public int maxSubArray(int[] nums) { + int n = nums.length; + int[] dp = new int[n]; + int maxSum = nums[0]; + dp[0] = nums[0]; + for(int i = 1; i < n; i++) { + if(dp[i-1] + nums[i] < nums[i]) { + dp[i] = nums[i]; + } else { + dp[i] = nums[i] + dp[i-1]; + } + maxSum = Math.max(maxSum, dp[i]); + } + return maxSum; + } +} From 871c2bca558eb94601fe8c2e34d2e0efc8422bbe Mon Sep 17 00:00:00 2001 From: Gotprgmer Date: Thu, 26 Dec 2024 16:29:20 +0900 Subject: [PATCH 066/183] add solution: Construct Binary Tree from Preorder and Inorder Traversal --- .../Gotprgmer.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 binary-tree-level-order-traversal/Gotprgmer.java diff --git a/binary-tree-level-order-traversal/Gotprgmer.java b/binary-tree-level-order-traversal/Gotprgmer.java new file mode 100644 index 000000000..43d646101 --- /dev/null +++ b/binary-tree-level-order-traversal/Gotprgmer.java @@ -0,0 +1,53 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ + +// preorder에서 맨 왼쪽을 root +// root값을 기반으로 inorder에서 인덱스를 찾는다 그리고 왼쪽 오른쪽 길이를 구한다. +// 다시 buildTree 함수를 재귀하는데 이때 위에서 구한 왼쪽 길이와 오른쪽길이를 참고해서 +// 왼쪽 buildTree +// value를 갱신 +// 오른쪽 buildTree를 갱신한다. + +// 시간복잡도 : O(N^2) -> 한쪽으로 치우친 트리일 경우 O(N)(index of) + T(N-1)이 될 수 있다. +// 위 식을 전개해보면 N + N-1 + N-2 + ... + 1 = N(N+1)/2 = O(N^2) +// 공간복잡도 : O(N) -> N길이의 리스트 크기 +class Solution { + public TreeNode buildTree(int[] preorder, int[] inorder) { + + if(preorder.length == 0 || indexOf(inorder,preorder[0]) == -1){ + return null; + } + TreeNode node = new TreeNode(); + + int root = preorder[0]; + int indexOfRoot = indexOf(inorder,root); + int leftCnt = indexOfRoot; + // 찾으면 + node.val = root; + node.left = buildTree(Arrays.copyOfRange(preorder,1,1+leftCnt),Arrays.copyOfRange(inorder,0,leftCnt)); + node.right = buildTree(Arrays.copyOfRange(preorder,1+leftCnt,preorder.length),Arrays.copyOfRange(inorder,1+leftCnt,inorder.length)); + return node; + } + public int indexOf(int[] intArray,int findNum){ + for(int i=0;i Date: Thu, 26 Dec 2024 16:29:44 +0900 Subject: [PATCH 067/183] fix solution: Construct Binary Tree from Preorder and Inorder Traversal --- binary-tree-level-order-traversal/Gotprgmer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/binary-tree-level-order-traversal/Gotprgmer.java b/binary-tree-level-order-traversal/Gotprgmer.java index 43d646101..8662dd83b 100644 --- a/binary-tree-level-order-traversal/Gotprgmer.java +++ b/binary-tree-level-order-traversal/Gotprgmer.java @@ -24,7 +24,7 @@ // 시간복잡도 : O(N^2) -> 한쪽으로 치우친 트리일 경우 O(N)(index of) + T(N-1)이 될 수 있다. // 위 식을 전개해보면 N + N-1 + N-2 + ... + 1 = N(N+1)/2 = O(N^2) // 공간복잡도 : O(N) -> N길이의 리스트 크기 -class Solution { +class SolutionGotprgmer { public TreeNode buildTree(int[] preorder, int[] inorder) { if(preorder.length == 0 || indexOf(inorder,preorder[0]) == -1){ From 130e5822e4184410dbdd58d5fc518001ee6fab3b Mon Sep 17 00:00:00 2001 From: mmyeon Date: Thu, 26 Dec 2024 16:51:23 +0900 Subject: [PATCH 068/183] add solution : 39. Combination Sum --- combination-sum/mmyeon.ts | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 combination-sum/mmyeon.ts diff --git a/combination-sum/mmyeon.ts b/combination-sum/mmyeon.ts new file mode 100644 index 000000000..e6f207953 --- /dev/null +++ b/combination-sum/mmyeon.ts @@ -0,0 +1,37 @@ +/** + * 접근 방법 : + * - 중복 포함하여 모든 조합 구해야 하니까 재귀함수로 풀기 + * - 재귀 호출로 탐색해야하는 타겟 줄여가면서 조합 만들기 + * - 동일 조합추가되지 않도록, startIndex 추가하여 다음 인덱스부터 순회하도록 제한 + * + * + * 시간복잡도 : O(n^target) + * - candidates 배열 길이 n만큼 재귀가 호출되고, 각 호출은 target 길이 만큼 중첩되니까 O(n^target) + * + * 공간복잡도 : O(target) + * - 최악의 경우 target만큼 재귀 호출되니까 O(target) + * + */ + +function combinationSum(candidates: number[], target: number): number[][] { + const result: number[][] = []; + + const dfs = (target: number, combination: number[], startIndex: number) => { + if (target === 0) { + result.push([...combination]); + return; + } + + if (target < 0) return; + + for (let i = startIndex; i < candidates.length; i++) { + combination.push(candidates[i]); + dfs(target - candidates[i], combination, i); + combination.pop(); + } + }; + + dfs(target, [], 0); + + return result; +} From 06da82c15f247a78aa7e161fd6bf7f996bb1d241 Mon Sep 17 00:00:00 2001 From: Gotprgmer Date: Thu, 26 Dec 2024 17:13:09 +0900 Subject: [PATCH 069/183] fix solution: Construct Binary Tree from Preorder and Inorder Traversal --- binary-tree-level-order-traversal/Gotprgmer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/binary-tree-level-order-traversal/Gotprgmer.java b/binary-tree-level-order-traversal/Gotprgmer.java index 8662dd83b..510c1f2e3 100644 --- a/binary-tree-level-order-traversal/Gotprgmer.java +++ b/binary-tree-level-order-traversal/Gotprgmer.java @@ -23,7 +23,7 @@ // 시간복잡도 : O(N^2) -> 한쪽으로 치우친 트리일 경우 O(N)(index of) + T(N-1)이 될 수 있다. // 위 식을 전개해보면 N + N-1 + N-2 + ... + 1 = N(N+1)/2 = O(N^2) -// 공간복잡도 : O(N) -> N길이의 리스트 크기 +// 공간복잡도 : O(N) ->리트코드 but N길이의 리스트 크기*N번의 재귀호출이 일어날 수 있다. 따라서 O(N^2)가 아닌가...? class SolutionGotprgmer { public TreeNode buildTree(int[] preorder, int[] inorder) { From fb485d94d420a03a6265597bc5b5e8566b86fe1a Mon Sep 17 00:00:00 2001 From: changchanghwang Date: Thu, 26 Dec 2024 17:19:05 +0900 Subject: [PATCH 070/183] feat: reverse bits --- reverse-bits/changchanghwang.go | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 reverse-bits/changchanghwang.go diff --git a/reverse-bits/changchanghwang.go b/reverse-bits/changchanghwang.go new file mode 100644 index 000000000..9f604dae2 --- /dev/null +++ b/reverse-bits/changchanghwang.go @@ -0,0 +1,6 @@ +// Time Complexity: O(1) +// Space Complexity: O(1) +func reverseBits(num uint32) uint32 { + reversedBits := bits.Reverse32(num) + return reversedBits +} From a3dbcb25f4ea7c4f687565929e91f73001265f53 Mon Sep 17 00:00:00 2001 From: changchanghwang Date: Thu, 26 Dec 2024 17:25:13 +0900 Subject: [PATCH 071/183] feat: product except self --- .../changchanghwang.go | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 product-of-array-except-self/changchanghwang.go diff --git a/product-of-array-except-self/changchanghwang.go b/product-of-array-except-self/changchanghwang.go new file mode 100644 index 000000000..5ffcbd92e --- /dev/null +++ b/product-of-array-except-self/changchanghwang.go @@ -0,0 +1,26 @@ +// time complexity: O(n) +// space complexity: O(1) +// prefix와 postfix를 이용하여 계산 +// 예를 들어, [1, 2, 3, 4] 일 때, +// prefix는 [1, 1, 2, 6] 이고 postfix는 [24, 12, 4, 1] 이다. +// 그리고 서로 곱하면 [24, 12, 8, 6] 이 된다. +func productExceptSelf(nums []int) []int { + res := make([]int, len(nums)) + for i := range res { + res[i] = 1 + } + + prefix := 1 + for i := 0; i < len(nums); i++ { + res[i] = prefix + prefix *= nums[i] + } + + postfix := 1 + for i := len(nums) - 1; i >= 0; i-- { + res[i] *= postfix + postfix *= nums[i] + } + + return res +} \ No newline at end of file From 4d19802e27294249d1c0206e69e5814858afbfda Mon Sep 17 00:00:00 2001 From: changchanghwang Date: Thu, 26 Dec 2024 17:46:16 +0900 Subject: [PATCH 072/183] fix: lint --- product-of-array-except-self/changchanghwang.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/product-of-array-except-self/changchanghwang.go b/product-of-array-except-self/changchanghwang.go index 5ffcbd92e..e6aaa51ac 100644 --- a/product-of-array-except-self/changchanghwang.go +++ b/product-of-array-except-self/changchanghwang.go @@ -23,4 +23,4 @@ func productExceptSelf(nums []int) []int { } return res -} \ No newline at end of file +} From 5a1ee896d691f9fad6220f3634520abf8937b017 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EC=9D=80=EB=B9=88=20Eunbeen=20Kang?= <145640625+river20s@users.noreply.github.com> Date: Thu, 26 Dec 2024 17:59:32 +0900 Subject: [PATCH 073/183] solution two sum --- two-sum/river20s.java | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 two-sum/river20s.java diff --git a/two-sum/river20s.java b/two-sum/river20s.java new file mode 100644 index 000000000..621660e25 --- /dev/null +++ b/two-sum/river20s.java @@ -0,0 +1,24 @@ +/* + * T.C: O(n) -> 배열 nums를 한 번 순회 + * S.C: O(n) → 최대 n개의 요소가 저장됨 + */ +import java.util.HashMap; + +class Solution { + public int[] twoSum(int[] nums, int target) { + + HashMap map = new HashMap<>(); + for (int i = 0; i < nums.length; i++) { + int k = target - nums[i]; + + if (map.containsKey(k)) { + return new int[] { map.get(k), i }; + } + + map.put(nums[i], i); + } + throw new IllegalArgumentException("exception handling for java compilation"); + + } +} + From 35ffaec8f38d7395d3d4ad027b5aa771b4470f41 Mon Sep 17 00:00:00 2001 From: Youngjae Kim Date: Thu, 26 Dec 2024 18:33:47 +0900 Subject: [PATCH 074/183] add: solve #234 Reverse Bits with ts --- reverse-bits/Yjason-K.ts | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 reverse-bits/Yjason-K.ts diff --git a/reverse-bits/Yjason-K.ts b/reverse-bits/Yjason-K.ts new file mode 100644 index 000000000..ff3cbb641 --- /dev/null +++ b/reverse-bits/Yjason-K.ts @@ -0,0 +1,22 @@ +/** + * 주어진 정수를 32비트로 변환하고 반전시켜 그때의 정수를 반환하는 문제. + * + * @param {number} n - 정수 (32비트)) + * @returns {number} - 2진수 변환 및 반전하여 정수 변환. + * + * 내장 메서드를 사용하여 32비트 2진수 변환 후, reverse하여 다시 정수로 변환. + * + * 시간 복잡도: O(32) + * - 32비트 정수의 비트를 처리하므로 고정된 상수 시간. + * + * 공간 복잡도: O(32) + * - 2진수 문자열을 생성하고 반전된 문자열을 저장하므로 고정된 크기의 추가 메모리가 필요. + */ +function reverseBits(n: number): number { + // 숫자를 32비트 2진수 문자열로 변환 (앞에 0 채우기) + const binaryStr = n.toString(2).padStart(32, '0'); + // 2진수 문자열을 뒤집기 + const reversedBinaryStr = binaryStr.split('').reverse().join(''); + // 뒤집힌 2진수 문자열을 다시 숫자로 변환 + return parseInt(reversedBinaryStr, 2); +}; From 494d56e75ddb4ef52999e91e65a49418b9dc330c Mon Sep 17 00:00:00 2001 From: forest000014 Date: Thu, 26 Dec 2024 21:29:44 +0900 Subject: [PATCH 075/183] Two Sum --- two-sum/forest000014.java | 64 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 two-sum/forest000014.java diff --git a/two-sum/forest000014.java b/two-sum/forest000014.java new file mode 100644 index 000000000..c414f5049 --- /dev/null +++ b/two-sum/forest000014.java @@ -0,0 +1,64 @@ +/* +runtime 23 ms, beats 50.28% +memory 45.12 MB, beats 20.14% + +time complexity: O(nlogn) +- numsArray 정렬: O(nlogn) +- binary search: O(nlogn) + - i iteration: O(n) + - i번째 binary search: O(logn) + +space complexity: O(n) +- numsArray: O(n) +*/ + +class Solution { + public int[] twoSum(int[] nums, int target) { + ArrayList numsArray = IntStream.range(0, nums.length) + .mapToObj(i -> new Tuple(i, nums[i])) + .collect(Collectors.toCollection(ArrayList::new)); + + numsArray.sort(Comparator.comparing(tuple -> tuple.val)); + + int n = numsArray.size(); + + for (int i = 0; i < n; i++) { + int x = target - numsArray.get(i).val; + int j = -1; + int l = i + 1; + int r = n - 1; + boolean found = false; + while (l <= r) { + int m = (r - l) / 2 + l; + if (numsArray.get(m).val == x) { + j = m; + found = true; + break; + } else if (numsArray.get(m).val < x) { + l = m + 1; + } else { + r = m - 1; + } + } + + if (found) { + int[] ans = new int[2]; + ans[0] = numsArray.get(i).ref; + ans[1] = numsArray.get(j).ref; + return ans; + } + } + + return null; + } + + public class Tuple { + public final Integer ref; + public final Integer val; + + public Tuple(Integer ref, Integer val) { + this.ref = ref; + this.val = val; + } + } +} \ No newline at end of file From b6138edd7576cc3c44f5700474aac50b596a4365 Mon Sep 17 00:00:00 2001 From: forest000014 Date: Thu, 26 Dec 2024 21:35:55 +0900 Subject: [PATCH 076/183] =?UTF-8?q?Two=20Sum=20-=20=EB=A7=88=EC=A7=80?= =?UTF-8?q?=EB=A7=89=20=EA=B0=9C=ED=96=89=20=EB=AC=B8=EC=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- two-sum/forest000014.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/two-sum/forest000014.java b/two-sum/forest000014.java index c414f5049..dc9f0436d 100644 --- a/two-sum/forest000014.java +++ b/two-sum/forest000014.java @@ -61,4 +61,4 @@ public Tuple(Integer ref, Integer val) { this.val = val; } } -} \ No newline at end of file +} From 8681b0439e4a5f28d48c805b88c394c180bffc63 Mon Sep 17 00:00:00 2001 From: forest000014 Date: Thu, 26 Dec 2024 22:18:57 +0900 Subject: [PATCH 077/183] Reverse Bits --- reverse-bits/forest000014.java | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 reverse-bits/forest000014.java diff --git a/reverse-bits/forest000014.java b/reverse-bits/forest000014.java new file mode 100644 index 000000000..c7e6818e8 --- /dev/null +++ b/reverse-bits/forest000014.java @@ -0,0 +1,24 @@ +/* +runtime 0 ms, beats 100.00% +memory 41.47 MB, beats 90.14% + +time complexity: O(1) +space complexity: O(1) + +i번째 bit를 구하고, 이를 ans(초기값 0)의 31-i번째 자리에 bitwise-OR 연산을 하여, bit 위치를 reverse 했습니다. +*/ + +public class Solution { + // you need treat n as an unsigned value + public int reverseBits(int n) { + int x = 1; + int ans = 0; + for (int i = 0; i < 32; i++) { + int bit = (x & n) >>> i; + bit <<= (31 - i); + ans |= bit; + x <<= 1; + } + return ans; + } +} From 78d9149346256ecbe04ef09a777447bf87c0aeb8 Mon Sep 17 00:00:00 2001 From: Dusuna <94776135+dusunax@users.noreply.github.com> Date: Thu, 26 Dec 2024 23:14:53 +0900 Subject: [PATCH 078/183] add solution: product-of-array-except-self --- product-of-array-except-self/dusunax.py | 34 +++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 product-of-array-except-self/dusunax.py diff --git a/product-of-array-except-self/dusunax.py b/product-of-array-except-self/dusunax.py new file mode 100644 index 000000000..27c13e828 --- /dev/null +++ b/product-of-array-except-self/dusunax.py @@ -0,0 +1,34 @@ +''' +# 238. Product of Array Except Self + +use prefix and suffix to calculate the product of the array, except self. + +## Time and Space Complexity + +``` +TC: O(n) +SC: O(n) +``` + +### TC is O(n): +- iterating through the list twice, to calculate both prefix and suffix products. = O(n) + +### SC is O(n): +- storing the prefix and suffix in the answer list. = O(n) +''' +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + n = len(nums) + answer = [1] * n + + # prefix + for i in range(1, n): + answer[i] *= nums[i - 1] * answer[i - 1] + + # suffix + suffix_product = 1 + for i in range(n - 1, -1, -1): + answer[i] *= suffix_product + suffix_product *= nums[i] + + return answer From 94d333f7381a8dee6d5132c85e9c24d6e38c15b4 Mon Sep 17 00:00:00 2001 From: Real-Reason Date: Wed, 25 Dec 2024 19:34:07 +0900 Subject: [PATCH 079/183] feat: solve two sum --- two-sum/Real-Reason.kt | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 two-sum/Real-Reason.kt diff --git a/two-sum/Real-Reason.kt b/two-sum/Real-Reason.kt new file mode 100644 index 000000000..acf6b33ae --- /dev/null +++ b/two-sum/Real-Reason.kt @@ -0,0 +1,16 @@ +package leetcode_study + +class `Real-Reason` { + fun twoSum(nums: IntArray, target: Int): IntArray { + for (startIdx in 0..< nums.size - 1) { + val firstNum = nums[startIdx] + for (endIdx in startIdx + 1..< nums.size) { + val secondNum = nums[endIdx] + if (target == firstNum + secondNum) { + return intArrayOf(startIdx, endIdx) + } + } + } + throw RuntimeException("There is no solution") + } +} \ No newline at end of file From 940096f2abbf88f109d7fc199928d153e43b5e1d Mon Sep 17 00:00:00 2001 From: Real-Reason Date: Thu, 26 Dec 2024 23:25:08 +0900 Subject: [PATCH 080/183] feat: solve product Except self --- product-of-array-except-self/Real-Reason.kt | 29 +++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 product-of-array-except-self/Real-Reason.kt diff --git a/product-of-array-except-self/Real-Reason.kt b/product-of-array-except-self/Real-Reason.kt new file mode 100644 index 000000000..85dc6d4cd --- /dev/null +++ b/product-of-array-except-self/Real-Reason.kt @@ -0,0 +1,29 @@ +package leetcode_study + +fun productExceptSelf(nums: IntArray): IntArray { + // ex. nums = [1, 2, 3, 4] + val leftStartProducts = mutableListOf(1) + val rightStartProducts = mutableListOf(1) + + // mutableNums = [1, 1, 2, 3, 4] + val mutableNums = nums.toMutableList() + mutableNums.add(0, 1) + mutableNums.add(1) + + // leftStartProducts = [1, 1, 2, 6, 24, 24] + // rightStartProducts = [24, 24, 24, 12, 4, 1] + for (idx in 1..< mutableNums.size) { + val leftNum = mutableNums[idx] + val rightNum = mutableNums[mutableNums.size - 1 - idx] + + leftStartProducts.add(leftStartProducts.last() * leftNum) + rightStartProducts.add(index = 0, element = rightStartProducts.first() * rightNum) + } + + val result = mutableListOf() + for (idx in 0..mutableNums.size - 3) { + result.add(leftStartProducts[idx] * rightStartProducts[idx + 2]) + } + + return result.toIntArray() +} \ No newline at end of file From 3762dae881b2ca59739fc5795d2235b9cc84ec46 Mon Sep 17 00:00:00 2001 From: Changhyun Lee Date: Thu, 26 Dec 2024 23:29:21 +0900 Subject: [PATCH 081/183] ADD : #219 # 234 #239 #254 #275 by heypaprika --- combination-sum/heypaprika.py | 20 ++++++++++++ maximum-subarray/heypaprika.py | 14 +++++++++ product-of-array-except-self/heypaprika.py | 36 ++++++++++++++++++++++ reverse-bits/heypaprika.py | 15 +++++++++ two-sum/heypaprika.py | 19 ++++++++++++ 5 files changed, 104 insertions(+) create mode 100644 combination-sum/heypaprika.py create mode 100644 maximum-subarray/heypaprika.py create mode 100644 product-of-array-except-self/heypaprika.py create mode 100644 reverse-bits/heypaprika.py create mode 100644 two-sum/heypaprika.py diff --git a/combination-sum/heypaprika.py b/combination-sum/heypaprika.py new file mode 100644 index 000000000..a94c06ed6 --- /dev/null +++ b/combination-sum/heypaprika.py @@ -0,0 +1,20 @@ +# 어렵네요ㅜ 보고 풀었습니다 + +class Solution: + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + ans = [] + def func(cur_remain, arr, idx): + if cur_remain == 0: + ans.append(list(arr)) + return + elif cur_remain < 0: + return + + for i in range(idx, len(candidates)): + arr.append(candidates[i]) + func(cur_remain - candidates[i], arr, i) + arr.pop() + + func(target, [], 0) + return ans + diff --git a/maximum-subarray/heypaprika.py b/maximum-subarray/heypaprika.py new file mode 100644 index 000000000..7493708b2 --- /dev/null +++ b/maximum-subarray/heypaprika.py @@ -0,0 +1,14 @@ +""" +복잡도 : 예상 -> 예상한 이유 + +시간 복잡도 : O(n) -> len(nums) 만큼 반복 +공간 복잡도 : O(n) -> len(nums) 크기의 배열 a 생성 +""" +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + a = [0] * len(nums) + a[0] = nums[0] + for i in range(1, len(nums)): + a[i] = max(nums[i], nums[i]+a[i-1]) + return max(a) + diff --git a/product-of-array-except-self/heypaprika.py b/product-of-array-except-self/heypaprika.py new file mode 100644 index 000000000..ad5b88d83 --- /dev/null +++ b/product-of-array-except-self/heypaprika.py @@ -0,0 +1,36 @@ +""" +복잡도 : 예상 -> 예상한 이유 + +시간 복잡도 : O(n) -> for 문이 여러번 있지만, len(nums)만큼 여러번 반복하므로 O(n) +공간 복잡도 : O(n) -> len(nums)만큼의 배열 하나가 더 생기므로 +""" +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + zeros = 0 + products = 1 + ans_list = [0] * len(nums) + + for i in range(len(nums)): + if nums[i] == 0: + zeros += 1 + products *= nums[i] + + if zeros == 1: + products = 1 + alived_i = -1 + for i in range(len(nums)): + if nums[i] == 0: + alived_i = i + continue + products *= nums[i] + ans_list[alived_i] = products + return ans_list + elif zeros >= 2: + return ans_list + + ans_list = [products] * len(nums) + for i in range(len(nums)): + ans_list[i] //= nums[i] + + return ans_list + diff --git a/reverse-bits/heypaprika.py b/reverse-bits/heypaprika.py new file mode 100644 index 000000000..cfbf85100 --- /dev/null +++ b/reverse-bits/heypaprika.py @@ -0,0 +1,15 @@ +""" +복잡도 : 예상 -> 예상한 이유 + +시간 복잡도 : O(1) -> 어떤 수가 들어오더라도 상수만큼 연산 +공간 복잡도 : O(1) -> 어떤 수가 들어오더라도 상수만큼 할당 +""" +class Solution: + def reverseBits(self, n: int) -> int: + ans = 0 + for i in range(32): + if n % 2 == 1: + ans += 2**(31-i) + n = n // 2 + return ans + diff --git a/two-sum/heypaprika.py b/two-sum/heypaprika.py new file mode 100644 index 000000000..f2c193b6a --- /dev/null +++ b/two-sum/heypaprika.py @@ -0,0 +1,19 @@ +""" +복잡도 : 예상 -> 예상한 이유 + +시간 복잡도 : O(n) -> 딕셔너리 키로 검색하는 것은 O(1), 따라서 for 문 1개로 O(n) +공간 복잡도 : O(n) -> n 수 만큼 반복되면서 값이 할당됨. +""" +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + num_dict = {} + n = len(nums) + + for i in range(n): + num_A = nums[i] + num_B = target - num_A + if num_B in num_dict: + return [i, num_dict[num_B]] + num_dict[num_A] = i + return [] + From 65e2454ab91da3415d56c9f6f997e68f678c752a Mon Sep 17 00:00:00 2001 From: forest000014 Date: Thu, 26 Dec 2024 23:55:57 +0900 Subject: [PATCH 082/183] Product of Array Except Self --- .../forest000014.java | 97 +++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 product-of-array-except-self/forest000014.java diff --git a/product-of-array-except-self/forest000014.java b/product-of-array-except-self/forest000014.java new file mode 100644 index 000000000..5a565faaf --- /dev/null +++ b/product-of-array-except-self/forest000014.java @@ -0,0 +1,97 @@ +/* +runtime 12 ms, beats 4.87% +memory 60.49 MB, beats 5.89% + +time complexity: O(n) +- nums 각각의 원소를 소인수분해 : O(10 * n) = O(n) +- ans[] 배열 계산 : O(n) + +space complexity: O(n) +- 2차원 배열(n * 10) - powers : O(n) +- 1차원 배열들(n) - minuses, ans: O(n) + +[풀이] +나눗셈이 금지되어 있기 때문에, 최대한 곱할 수 있는 만큼을 미리 곱해놓고, i번째 원소마다 부족한 부분만큼을 나중에 채워 넣어 곱해주는 방식으로 접근했습니다. +nums[i]의 절대값이 30 이하인 점에 착안해서, nums[i]는 많아야 10개의 base로 소인수 분해가 가능하다는 점을 떠올렸습니다. 따라서 각각의 base마다 (nums 전체에서 등장한 base의 지수의 총합) - (nums[i]의 base의 지수 중 가장 큰 값) 만큼의 지수로 미리 곱해주고, i에 대한 iteration에서 부족한 지수만큼을 보충해서 곱해주었습니다. +(풀이를 쓰다 보니, 실제 코드에서 이렇게 미리 곱해 놓은 수를 base라고 명명한 게 혼동될 수 있겠네요...^^;) + +이 풀이에서 아쉬운 점이 여전히 있습니다. 시간 복잡도를 따지면 O(10*n) = O(n)이니 문제의 조건을 맞췄다고 할 수도 있겠지만, 상수가 좀 크다는 점이 마음에 걸리네요. +(for (int j = 0; j < 10 && abs > 1; j++) <--- 여기에서 abs == 1이 되면 for-loop를 빠져나가게 했지만, nums[i]가 모두 29로 차있는 edge case라면 10*n을 꽉 채우게 되니까요.) + +이 풀이 말고도, nums[]를 2개로 나눈 블럭, 4개로 나눈 블럭, 8개로 나눈 블럭, ... 이런 식으로 사이즈 별로 블럭을 나눠두고, 각각의 블럭 내부의 곱을 미리 계산해두는 방식도 생각해보았습니다. 이러면 시간 복잡도와 공간 복잡도가 모두 O(nlogn)이 나올 것 같습니다. (사실 이 풀이를 가장 처음에 떠올렸습니다만, O(n)으로 줄이는 고민을 하다가 현재 제출한 풀이를 떠올리고서는 이 풀이는 구현을 안 했습니다. 시간이 되면 이렇게도 풀어보고, 좀 더 디벨롭을 해봐야겠네요.) +*/ +class Solution { + public int[] productExceptSelf(int[] nums) { + int n = nums.length; + + int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; + int[][] powers = new int[n][10]; + int[] sumPowers = new int[10]; + int[] maxPowers = new int[10]; + + boolean[] minuses = new boolean[n]; + + int base = 1; + + int[] ans = new int[n]; + + for (int i = 0; i < n; i++) { + if (nums[i] == 0) { + int x = 1; + for (int j = 0; j < n; j++) { + if (j == i) { + continue; + } + ans[j] = 0; + x *= nums[j]; + } + ans[i] = x; + + return ans; + } + + int abs; + if (nums[i] > 0) { + abs = nums[i]; + } else { + abs = -nums[i]; + base = -base; + minuses[i] = true; + } + + for (int j = 0; j < 10 && abs > 1; j++) { + int curPower = 0; + while (abs % primes[j] == 0) { + powers[i][j]++; + sumPowers[j]++; + curPower++; + abs /= primes[j]; + } + if (curPower > maxPowers[j]) { + maxPowers[j] = curPower; + } + } + } + + for (int i = 0; i < 10; i++) { + for (int j = 0; j < sumPowers[i] - maxPowers[i]; j++) { + base *= primes[i]; + } + } + + for (int i = 0; i < n; i++) { + ans[i] = base; + for (int j = 0; j < 10; j++) { + for (int k = 0; k < maxPowers[j] - powers[i][j]; k++) { + ans[i] *= primes[j]; + } + } + if (minuses[i]) { + ans[i] = -ans[i]; + } + } + + + return ans; + } +} From 9e5e459cce53035ca80ccd20de8c499e57145259 Mon Sep 17 00:00:00 2001 From: Taewan Lim Date: Fri, 27 Dec 2024 00:01:53 +0900 Subject: [PATCH 083/183] combination-sum --- combination-sum/taewanseoul.ts | 37 ++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 combination-sum/taewanseoul.ts diff --git a/combination-sum/taewanseoul.ts b/combination-sum/taewanseoul.ts new file mode 100644 index 000000000..73c2ba67b --- /dev/null +++ b/combination-sum/taewanseoul.ts @@ -0,0 +1,37 @@ +/** + * 39. Combination Sum + * Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. + * The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different. + * The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input. + * + * https://leetcode.com/problems/combination-sum/description/ + */ + +// O(n^m) time +// O(n) space +function combinationSum(candidates: number[], target: number): number[][] { + const res: number[][] = []; + dfs(candidates, 0, target, [], res); + return res; +} + +function dfs( + nums: number[], + start: number, + remaining: number, + path: number[], + res: number[][] +) { + if (remaining === 0) { + res.push([...path]); + return; + } + + for (let i = start; i < nums.length; i++) { + const num = nums[i]; + if (remaining - num < 0) continue; + path.push(num); + dfs(nums, i, remaining - num, path, res); + path.pop(); + } +} From 9c068d63cf5257c80e3764acf9fa7990bfac37d0 Mon Sep 17 00:00:00 2001 From: forest000014 Date: Fri, 27 Dec 2024 00:16:06 +0900 Subject: [PATCH 084/183] Product of Array Except Self - space complexity O(1) --- .../forest000014.java | 30 +++++++++++-------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/product-of-array-except-self/forest000014.java b/product-of-array-except-self/forest000014.java index 5a565faaf..c7cc473c6 100644 --- a/product-of-array-except-self/forest000014.java +++ b/product-of-array-except-self/forest000014.java @@ -1,14 +1,16 @@ /* -runtime 12 ms, beats 4.87% -memory 60.49 MB, beats 5.89% +runtime 8 ms, beats 4.87% +memory 55.44 MB, beats 54.17% time complexity: O(n) - nums 각각의 원소를 소인수분해 : O(10 * n) = O(n) -- ans[] 배열 계산 : O(n) +- ans[] 배열 계산 : O(10 * n) + - i, j, k의 3중 for-loop가 O(n * 10 * 4) 처럼 보일 수 있는데요(10은 소인수 분해 base의 개수, 4는 power중 최대값), + - 실제로는 k가 큰 경우에는 j-loop가 일찍 끝나고 (예컨대 nums[i] = 2^4 인 경우에는, base가 2에서 끝나니 j-loop가 j=1에서 끝남) + - j가 큰 경우에는 k-loop가 일찍 끝나므로 (예컨대 num[i] = 29인 경우에는, k-loop가 1에서 끝남) + - 최악의 경우에 O(n * 10) 정도로 보는 게 타당하다고 생각합니다. -space complexity: O(n) -- 2차원 배열(n * 10) - powers : O(n) -- 1차원 배열들(n) - minuses, ans: O(n) +space complexity: O(1) [풀이] 나눗셈이 금지되어 있기 때문에, 최대한 곱할 수 있는 만큼을 미리 곱해놓고, i번째 원소마다 부족한 부분만큼을 나중에 채워 넣어 곱해주는 방식으로 접근했습니다. @@ -17,6 +19,7 @@ 이 풀이에서 아쉬운 점이 여전히 있습니다. 시간 복잡도를 따지면 O(10*n) = O(n)이니 문제의 조건을 맞췄다고 할 수도 있겠지만, 상수가 좀 크다는 점이 마음에 걸리네요. (for (int j = 0; j < 10 && abs > 1; j++) <--- 여기에서 abs == 1이 되면 for-loop를 빠져나가게 했지만, nums[i]가 모두 29로 차있는 edge case라면 10*n을 꽉 채우게 되니까요.) +그래도 어쨌든 문제의 조건을 최대한 활용해서 시도해볼만한 접근이라고 생각합니다. 이 풀이 말고도, nums[]를 2개로 나눈 블럭, 4개로 나눈 블럭, 8개로 나눈 블럭, ... 이런 식으로 사이즈 별로 블럭을 나눠두고, 각각의 블럭 내부의 곱을 미리 계산해두는 방식도 생각해보았습니다. 이러면 시간 복잡도와 공간 복잡도가 모두 O(nlogn)이 나올 것 같습니다. (사실 이 풀이를 가장 처음에 떠올렸습니다만, O(n)으로 줄이는 고민을 하다가 현재 제출한 풀이를 떠올리고서는 이 풀이는 구현을 안 했습니다. 시간이 되면 이렇게도 풀어보고, 좀 더 디벨롭을 해봐야겠네요.) */ @@ -25,12 +28,9 @@ public int[] productExceptSelf(int[] nums) { int n = nums.length; int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; - int[][] powers = new int[n][10]; int[] sumPowers = new int[10]; int[] maxPowers = new int[10]; - boolean[] minuses = new boolean[n]; - int base = 1; int[] ans = new int[n]; @@ -56,13 +56,11 @@ public int[] productExceptSelf(int[] nums) { } else { abs = -nums[i]; base = -base; - minuses[i] = true; } for (int j = 0; j < 10 && abs > 1; j++) { int curPower = 0; while (abs % primes[j] == 0) { - powers[i][j]++; sumPowers[j]++; curPower++; abs /= primes[j]; @@ -82,11 +80,17 @@ public int[] productExceptSelf(int[] nums) { for (int i = 0; i < n; i++) { ans[i] = base; for (int j = 0; j < 10; j++) { - for (int k = 0; k < maxPowers[j] - powers[i][j]; k++) { + int tmp = nums[i]; + int power = 0; + while (tmp % primes[j] == 0) { + power++; + tmp /= primes[j]; + } + for (int k = 0; k < maxPowers[j] - power; k++) { ans[i] *= primes[j]; } } - if (minuses[i]) { + if (nums[i] < 0) { ans[i] = -ans[i]; } } From f9cabb58c4d2475550c04897e1ecf62ed3cf0f69 Mon Sep 17 00:00:00 2001 From: Lyla Date: Thu, 26 Dec 2024 10:22:31 -0500 Subject: [PATCH 085/183] solved --- combination-sum/pmjuu.py | 33 +++++++++++++++++++++ maximum-subarray/pmjuu.py | 20 +++++++++++++ product-of-array-except-self/pmjuu.py | 27 +++++++++++++++++ reverse-bits/pmjuu.py | 42 +++++++++++++++++++++++++++ two-sum/pmjuu.py | 20 +++++++++++++ 5 files changed, 142 insertions(+) create mode 100644 combination-sum/pmjuu.py create mode 100644 maximum-subarray/pmjuu.py create mode 100644 product-of-array-except-self/pmjuu.py create mode 100644 reverse-bits/pmjuu.py create mode 100644 two-sum/pmjuu.py diff --git a/combination-sum/pmjuu.py b/combination-sum/pmjuu.py new file mode 100644 index 000000000..af2bfcb8e --- /dev/null +++ b/combination-sum/pmjuu.py @@ -0,0 +1,33 @@ +from typing import List + + +class Solution: + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + result = [] + + def backtrack(start, target, current_combination): + # 종료 조건 + if target == 0: + result.append(list(current_combination)) + return + if target < 0: + return + + # 백트래킹 + for i in range(start, len(candidates)): + current_combination.append(candidates[i]) + backtrack(i, target - candidates[i], current_combination) # 같은 원소를 여러 번 쓸 수 있도록 i를 그대로 둡니다. + current_combination.pop() # 돌아가서 다시 시도할 수 있도록 원소를 제거합니다. + + backtrack(0, target, []) + + return result + + +# 시간 복잡도: O(n^t) +# - 후보 리스트에서 각 숫자를 선택할 수 있기 때문에, n개의 후보를 사용해 t번의 탐색을 할 수 있습니다. +# - 따라서 최악의 경우 탐색 횟수는 O(n^t)로 볼 수 있습니다. +# +# 공간 복잡도: O(t) +# - 재귀 호출 스택의 깊이는 최대 target 값인 t에 비례하므로, 공간 복잡도는 O(t)입니다. +# - 또한, 현재까지 선택된 숫자들의 조합을 저장하는 공간도 최대 t개까지 저장하므로, 공간 복잡도는 O(t)입니다. diff --git a/maximum-subarray/pmjuu.py b/maximum-subarray/pmjuu.py new file mode 100644 index 000000000..0cf0aa22e --- /dev/null +++ b/maximum-subarray/pmjuu.py @@ -0,0 +1,20 @@ +from typing import List + + +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + largest_sum = -float('inf') + current_sum = -float('inf') + + for num in nums: + current_sum = max(current_sum + num, num) + largest_sum = max(largest_sum, current_sum) + + return largest_sum + + +# 시간 복잡도: O(n) +# - nums 배열을 한 번 순회하며 각 요소에 대해 최대 부분 배열 합을 계산하므로 시간 복잡도는 O(n)입니다. +# +# 공간 복잡도: O(1) +# - 추가로 사용하는 변수는 largest_sum과 current_sum 두 개뿐이므로 공간 복잡도는 O(1)입니다. diff --git a/product-of-array-except-self/pmjuu.py b/product-of-array-except-self/pmjuu.py new file mode 100644 index 000000000..0b8fb15ee --- /dev/null +++ b/product-of-array-except-self/pmjuu.py @@ -0,0 +1,27 @@ +from typing import List + + +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + n = len(nums) + result = [1] * n + + prefix = 1 + for i in range(n): + result[i] *= prefix + prefix *= nums[i] + + suffix = 1 + for i in range(-1, -n-1, -1): + result[i] *= suffix + suffix *= nums[i] + + return result + + +# 시간 복잡도: O(n) +# - 입력 배열 nums를 두 번 순회합니다. +# +# 공간 복잡도: O(1) +# - 추가 공간으로 사용하는 변수는 prefix와 suffix뿐이며, +# 출력 배열(result)은 추가 공간으로 계산하지 않습니다. diff --git a/reverse-bits/pmjuu.py b/reverse-bits/pmjuu.py new file mode 100644 index 000000000..cd8d240aa --- /dev/null +++ b/reverse-bits/pmjuu.py @@ -0,0 +1,42 @@ +class Solution: + def reverseBits(self, n: int) -> int: + # 이진수로 변환한 후 '0b' 제거 + binary = bin(n)[2:] + # 32비트 길이에 맞게 앞쪽에 0을 채움 + binary = binary.zfill(32) + # 이진수를 뒤집음 + reversed_binary = binary[::-1] + # 뒤집힌 이진수를 정수로 변환하여 반환 + return int(reversed_binary, 2) + + +# 시간 복잡도: O(32) +# - bin(): O(32) +# - zfill(32): O(32) +# - 문자열 뒤집기 [::-1]: O(32) +# - int(문자열, 2): O(32) +# 총합: O(32) (상수 시간으로 간주 가능) + +# 공간 복잡도: O(32) +# - 이진 문자열(binary)와 뒤집힌 문자열(reversed_binary)을 저장하므로 O(32). + + +class Solution: + def reverseBits(self, n: int) -> int: + result = 0 + + for i in range(32): + # result를 왼쪽으로 1비트 이동하고 n의 마지막 비트를 추가 + result = (result << 1) | n & 1 + # n을 오른쪽으로 1비트 이동 + n >>= 1 + + return result + + +# 시간 복잡도: O(32) +# - 반복문이 32번 실행되며 각 작업(비트 이동 및 OR 연산)은 O(1). +# 총합: O(32) (상수 시간으로 간주 가능) + +# 공간 복잡도: O(1) +# - 추가로 사용하는 변수 result와 n만 저장하므로 상수 공간. diff --git a/two-sum/pmjuu.py b/two-sum/pmjuu.py new file mode 100644 index 000000000..051992221 --- /dev/null +++ b/two-sum/pmjuu.py @@ -0,0 +1,20 @@ +from typing import List + + +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + subtract_map = {} + + for i, num in enumerate(nums): + if num in subtract_map: + return [i, subtract_map[num]] + else: + subtract_map[target - num] = i + + +# 시간 복잡도: O(n) +# - nums 배열을 한 번 순회하며 각 요소를 확인하므로 시간 복잡도는 O(n)입니다. +# +# 공간 복잡도: O(n) +# - 추가로 사용하는 subtract_map 딕셔너리에는 최악의 경우 nums 배열의 모든 요소가 저장되므로 +# 공간 복잡도는 O(n)입니다. From e8d4b4a500787fec1a308581d75d785ddc275fa3 Mon Sep 17 00:00:00 2001 From: Youngjae Kim Date: Fri, 27 Dec 2024 00:22:45 +0900 Subject: [PATCH 086/183] add: solve #241 3Sum with ts --- 3sum/Yjason-K.ts | 52 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 3sum/Yjason-K.ts diff --git a/3sum/Yjason-K.ts b/3sum/Yjason-K.ts new file mode 100644 index 000000000..ad481c049 --- /dev/null +++ b/3sum/Yjason-K.ts @@ -0,0 +1,52 @@ +/** + * 세 수의 합이 0이 되는 모든 고유한 조합을 찾는 함수 + * + * @param {number[]} nums - 정수 배열 + * @returns {number[][]} - 세 수의 합이 0이 되는 조합 배열 + * + * 1. 입력 배열 `nums`를 오름차순으로 정렬. + * 2. 이중 반복문을 사용하여 각 요소를 기준으로 `투 포인터(two-pointer)`를 이용해 조합을 탐색. + * 3. 중복 조합을 방지하기 위해 `Set`을 사용하여 결과 조합의 문자열을 저장. + * 4. 조건에 맞는 조합을 `result` 배열에 추가합니다. + * + * 시간 복잡도: + * - 정렬: O(n log n) + * - 이중 반복문 및 투 포인터: O(n^2) + * - 전체 시간 복잡도: O(n^2) + * + * 공간 복잡도: + * - `Set` 및 `result` 배열에 저장되는 고유 조합: O(k), k는 고유한 조합의 수 + * - 전체 공간 복잡도: O(n + k) + */ +function threeSum(nums: number[]): number[][] { + const sumSet = new Set(); + const result: number[][] = []; + nums.sort((a, b) => a - b); + + // 첫 번째 요소를 기준으로 반복문 수행 + for (let i = 0; i < nums.length - 2; i++) { + // 정렬 된 상태이기 때문에 시작점을 기준으로 다음 값 중복 비교 + if (i > 0 && nums[i] === nums[i - 1]) continue; + + let start = i + 1, end = nums.length - 1; + while (start < end) { + const sum = nums[i] + nums[start] + nums[end]; + if (sum > 0) { + end--; + } else if (sum < 0) { + start++; + } else { + const triplet = [nums[i], nums[start], nums[end]]; + const key = triplet.toString(); + if (!sumSet.has(key)) { + sumSet.add(key); + result.push(triplet); + } + start++; + end--; + } + } + } + + return result; +} \ No newline at end of file From 2d670218f9fc5bd9e3e8c1597813b8d214cdefaa Mon Sep 17 00:00:00 2001 From: minji-go Date: Fri, 27 Dec 2024 00:32:00 +0900 Subject: [PATCH 087/183] feat: maximum subarray --- maximum-subarray/minji-go.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 maximum-subarray/minji-go.java diff --git a/maximum-subarray/minji-go.java b/maximum-subarray/minji-go.java new file mode 100644 index 000000000..617d215a7 --- /dev/null +++ b/maximum-subarray/minji-go.java @@ -0,0 +1,18 @@ +/* + Problem: https://leetcode.com/problems/maximum-subarray/ + Description: return the largest sum of the subarray, contiguous non-empty sequence of elements within an array. + Concept: Array, Divide and Conquer, Dynamic Programming + Time Complexity: O(N), Runtime 1ms + Space Complexity: O(1), Memory 57.02MB +*/ +class Solution { + public int maxSubArray(int[] nums) { + int max = nums[0]; + int sum = nums[0]; + for(int i=1; i Date: Fri, 27 Dec 2024 00:32:47 +0900 Subject: [PATCH 088/183] feat: product of array except self --- product-of-array-except-self/minji-go.java | 24 ++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 product-of-array-except-self/minji-go.java diff --git a/product-of-array-except-self/minji-go.java b/product-of-array-except-self/minji-go.java new file mode 100644 index 000000000..62d19204c --- /dev/null +++ b/product-of-array-except-self/minji-go.java @@ -0,0 +1,24 @@ +/* + Problem: https://leetcode.com/problems/product-of-array-except-self/ + Description: return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. + Concept: Array, Prefix Sum + Time Complexity: O(N), Runtime 5ms + Space Complexity: O(N), Memory 54.6MB - O(1) except the output array +*/ +class Solution { + public int[] productExceptSelf(int[] nums) { + int[] answer = new int[nums.length]; + Arrays.fill(answer, 1); + + int prefixProduct = 1; + int suffixProduct = 1; + for(int i=1; i Date: Fri, 27 Dec 2024 00:59:14 +0900 Subject: [PATCH 089/183] feat: solve combination sum --- combination-sum/Real-Reason.kt | 23 +++++++++++++++++++++ product-of-array-except-self/Real-Reason.kt | 2 +- two-sum/Real-Reason.kt | 2 +- 3 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 combination-sum/Real-Reason.kt diff --git a/combination-sum/Real-Reason.kt b/combination-sum/Real-Reason.kt new file mode 100644 index 000000000..bce40e84f --- /dev/null +++ b/combination-sum/Real-Reason.kt @@ -0,0 +1,23 @@ +package leetcode_study + +fun combinationSum(candidates: IntArray, target: Int): List> { + val result = mutableListOf>() + val nums = ArrayDeque() + dfs(candidates, target, 0, 0, nums, result) + + return result +} + +private fun dfs(candidates: IntArray, target: Int, startIdx: Int, total: Int, nums: ArrayDeque, result: MutableList>) { + if (target < total) return + if (target == total) { + result.add(ArrayList(nums)) + return + } + for (i in startIdx..< candidates.size) { + val num = candidates[i] + nums.add(num) + dfs(candidates, target, i, total + num, nums, result) + nums.removeLast() + } +} diff --git a/product-of-array-except-self/Real-Reason.kt b/product-of-array-except-self/Real-Reason.kt index 85dc6d4cd..039f93356 100644 --- a/product-of-array-except-self/Real-Reason.kt +++ b/product-of-array-except-self/Real-Reason.kt @@ -26,4 +26,4 @@ fun productExceptSelf(nums: IntArray): IntArray { } return result.toIntArray() -} \ No newline at end of file +} diff --git a/two-sum/Real-Reason.kt b/two-sum/Real-Reason.kt index acf6b33ae..84e1952f8 100644 --- a/two-sum/Real-Reason.kt +++ b/two-sum/Real-Reason.kt @@ -13,4 +13,4 @@ class `Real-Reason` { } throw RuntimeException("There is no solution") } -} \ No newline at end of file +} From 79627edd02f78519cc768a9dba83263a4010965f Mon Sep 17 00:00:00 2001 From: mintheon Date: Fri, 27 Dec 2024 01:16:23 +0900 Subject: [PATCH 090/183] two-sum solved --- two-sum/mintheon.java | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 two-sum/mintheon.java diff --git a/two-sum/mintheon.java b/two-sum/mintheon.java new file mode 100644 index 000000000..5c53b7f89 --- /dev/null +++ b/two-sum/mintheon.java @@ -0,0 +1,26 @@ +import java.util.HashMap; +import java.util.Map; + +class Solution { + /** + 공간복잡도: O(n) + 시간복잡도: O(n) + */ + + public int[] twoSum(int[] nums, int target) { + Map numMap = new HashMap<>(); + + for(int i = 0; i < nums.length; i++) { + numMap.put(nums[i], i); + } + + for(int i = 0; i < nums.length; i++) { + int pairNum = target - nums[i]; + if(numMap.containsKey(pairNum) && numMap.get(pairNum) != i) { + return new int[]{i, numMap.get(target - nums[i])}; + } + } + + return new int[2]; + } +} From 8b91fc33e5d7170b5e07d0ec8ec7e9153fd55cb1 Mon Sep 17 00:00:00 2001 From: Jaehyeon Robert Han Date: Thu, 26 Dec 2024 15:26:28 -0800 Subject: [PATCH 091/183] combination-sum solution --- combination-sum/Zioq.js | 44 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 combination-sum/Zioq.js diff --git a/combination-sum/Zioq.js b/combination-sum/Zioq.js new file mode 100644 index 000000000..cb019a87f --- /dev/null +++ b/combination-sum/Zioq.js @@ -0,0 +1,44 @@ +/** + * @param {number[]} candidates + * @param {number} target + * @return {number[][]} + */ +var combinationSum = function(candidates, target) { + let result = []; + + function find_combination(index, target, current) { + if (target === 0) { + result.push([...current]); + return; + } + + for (let i = index; i < candidates.length; i++) { + // Only proceed if current number doesn't exceed target + if (candidates[i] <= target) { + // Include current number in combination + current.push(candidates[i]); + + // Recursive call with: + // - same index i (allowing reuse of same number) + // - reduced target by current number + find_combination(i, target - candidates[i], current); + + // Backtrack: remove the last added number to try other combinations + current.pop(); + } + } + } + + find_combination(0, target, []); + return result; +}; + +/* + + + +*/ + +console.log(combinationSum([2,3,6,7], 7)) + + From 15e1e1409ae094eb8bce12de2b42cd243050d6e5 Mon Sep 17 00:00:00 2001 From: Paik Date: Fri, 27 Dec 2024 09:15:25 +0900 Subject: [PATCH 092/183] feat: 1. Two Sum --- two-sum/gwbaik9717.js | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 two-sum/gwbaik9717.js diff --git a/two-sum/gwbaik9717.js b/two-sum/gwbaik9717.js new file mode 100644 index 000000000..d5f3ae7f5 --- /dev/null +++ b/two-sum/gwbaik9717.js @@ -0,0 +1,33 @@ +// Time complexity: O(nlogn) +// Space complexity: O(n) + +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var twoSum = function (nums, target) { + const n = nums.length; + + const mappedNums = nums.map((num, i) => [num, i]); + mappedNums.sort((a, b) => a[0] - b[0]); + + let left = 0; + let right = n - 1; + + while (left < right) { + const sum = mappedNums[left][0] + mappedNums[right][0]; + + if (sum > target) { + right--; + continue; + } + + if (sum < target) { + left++; + continue; + } + + return [mappedNums[left][1], mappedNums[right][1]]; + } +}; From 2d87ed600c017b3e7fdb30019ef8e2c04be3826b Mon Sep 17 00:00:00 2001 From: easyone Date: Fri, 27 Dec 2024 09:33:54 +0900 Subject: [PATCH 093/183] Feat: Add solution of reverse-bits. --- reverse-bits/easyone-jwlee.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 reverse-bits/easyone-jwlee.go diff --git a/reverse-bits/easyone-jwlee.go b/reverse-bits/easyone-jwlee.go new file mode 100644 index 000000000..c59a8420a --- /dev/null +++ b/reverse-bits/easyone-jwlee.go @@ -0,0 +1,20 @@ +// 풀이 +// result 가장 오른쪽 값에 num의 값을 추가하면서 왼쪽으로 밀어 reverse 처리. + +// TC +// for문은 무조건 32회만 돌기때문에 O(1) + +// SC +// 추가적인 공간 사용량은 일정하므로 0(1) + +func reverseBits(num uint32) uint32 { + result := uint32(0) + for i := 0; i < 32; i++ { + result <<= 1 + if num%2 == 1 { + result++ + } + num >>= 1 + } + return result +} \ No newline at end of file From f00f3fc07843b1b66672ef28014e86eb5e44f812 Mon Sep 17 00:00:00 2001 From: easyone Date: Fri, 27 Dec 2024 09:35:36 +0900 Subject: [PATCH 094/183] Fix: Edit lint. --- reverse-bits/easyone-jwlee.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reverse-bits/easyone-jwlee.go b/reverse-bits/easyone-jwlee.go index c59a8420a..506482548 100644 --- a/reverse-bits/easyone-jwlee.go +++ b/reverse-bits/easyone-jwlee.go @@ -17,4 +17,4 @@ func reverseBits(num uint32) uint32 { num >>= 1 } return result -} \ No newline at end of file +} From 2530b0f91d4b06eaa2f80b2bda1998e2b461ce8d Mon Sep 17 00:00:00 2001 From: Paik Date: Fri, 27 Dec 2024 10:46:47 +0900 Subject: [PATCH 095/183] refactor: feat: 1. Two Sum --- two-sum/gwbaik9717.js | 29 +++++++++-------------------- 1 file changed, 9 insertions(+), 20 deletions(-) diff --git a/two-sum/gwbaik9717.js b/two-sum/gwbaik9717.js index d5f3ae7f5..c7b1397de 100644 --- a/two-sum/gwbaik9717.js +++ b/two-sum/gwbaik9717.js @@ -1,4 +1,4 @@ -// Time complexity: O(nlogn) +// Time complexity: O(n) // Space complexity: O(n) /** @@ -7,27 +7,16 @@ * @return {number[]} */ var twoSum = function (nums, target) { - const n = nums.length; + const map = new Map(); - const mappedNums = nums.map((num, i) => [num, i]); - mappedNums.sort((a, b) => a[0] - b[0]); + for (let i = 0; i < nums.length; i++) { + const num = nums[i]; + const diff = target - num; - let left = 0; - let right = n - 1; - - while (left < right) { - const sum = mappedNums[left][0] + mappedNums[right][0]; - - if (sum > target) { - right--; - continue; + if (map.has(diff)) { + return [i, map.get(diff)]; + } else { + map.set(num, i); } - - if (sum < target) { - left++; - continue; - } - - return [mappedNums[left][1], mappedNums[right][1]]; } }; From 5bf74c8c11d8d053a27e62739889f569e355e4a3 Mon Sep 17 00:00:00 2001 From: Minji Go Date: Fri, 27 Dec 2024 11:19:35 +0900 Subject: [PATCH 096/183] feat: combination sum --- combination-sum/minji-go.java | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 combination-sum/minji-go.java diff --git a/combination-sum/minji-go.java b/combination-sum/minji-go.java new file mode 100644 index 000000000..ab895923a --- /dev/null +++ b/combination-sum/minji-go.java @@ -0,0 +1,33 @@ +/* + Problem: https://leetcode.com/problems/combination-sum/ + Description: return a list of all unique combinations of candidates where the chosen numbers sum to target + Concept: Array, Backtracking + Time Complexity: O(Nⁿ), Runtime 2ms + Space Complexity: O(N), Memory 44.88MB + + - Time Complexity, Space Complexity를 어떻게 계산해야할지 어렵네요 :( +*/ +class Solution { + public List> answer = new ArrayList<>(); + + public List> combinationSum(int[] candidates, int target) { + Arrays.sort(candidates); + findCombination(candidates, target, new ArrayList<>(), 0); + return answer; + } + + public void findCombination(int[] candidates, int target, List combination, int idx) { + if(target == 0) { + answer.add(new ArrayList<>(combination)); + return; + } + + for(int i=idx; i target) break; + + combination.add(candidates[i]); + findCombination(candidates, target-candidates[i], combination, i); + combination.remove(combination.size()-1); + } + } +} From 566f0f9353540760d63d7d293610182466ace868 Mon Sep 17 00:00:00 2001 From: jinah92 Date: Fri, 27 Dec 2024 11:22:33 +0900 Subject: [PATCH 097/183] =?UTF-8?q?feat:=20week3=20easy=20=EB=AC=B8?= =?UTF-8?q?=EC=A0=9C=20=ED=92=80=EC=9D=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- reverse-bits/jinah92.py | 14 ++++++++++++++ two-sum/jinah92.py | 12 ++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 reverse-bits/jinah92.py create mode 100644 two-sum/jinah92.py diff --git a/reverse-bits/jinah92.py b/reverse-bits/jinah92.py new file mode 100644 index 000000000..4d2d8cf5e --- /dev/null +++ b/reverse-bits/jinah92.py @@ -0,0 +1,14 @@ +# O(1) time, O(1) space +class Solution: + def reverseBits(self, n: int) -> int: + stack = [] + while len(stack) < 32: + stack.append(n % 2) + n //=2 + + result, scale = 0, 1 + while stack: + result += stack.pop() * scale + scale *= 2 + + return result diff --git a/two-sum/jinah92.py b/two-sum/jinah92.py new file mode 100644 index 000000000..e8b204155 --- /dev/null +++ b/two-sum/jinah92.py @@ -0,0 +1,12 @@ +# O(n) time, O(n) space + +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + num_set = {} + + for idx, num in enumerate(nums): + other_num = target - num + if other_num in num_set: + return [idx, num_set[other_num]] + else: + num_set[num] = idx From cbce8b10480b33d270f1ef7ba4a980c4768ccf59 Mon Sep 17 00:00:00 2001 From: jinah92 Date: Fri, 27 Dec 2024 11:48:47 +0900 Subject: [PATCH 098/183] =?UTF-8?q?feat:=20week3=20medium=20=EB=AC=B8?= =?UTF-8?q?=EC=A0=9C=ED=92=80=EC=9D=B4(product-of-array-except-self)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- product-of-array-except-self/jinah92.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 product-of-array-except-self/jinah92.py diff --git a/product-of-array-except-self/jinah92.py b/product-of-array-except-self/jinah92.py new file mode 100644 index 000000000..68bb85e2b --- /dev/null +++ b/product-of-array-except-self/jinah92.py @@ -0,0 +1,21 @@ +# O(n) time, O(n) space +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + non_zero_product = math.prod(filter(lambda x: x != 0, nums)) + raw_product = math.prod(nums) + zero_total = nums.count(0) + + result = [] + + for num in nums: + if zero_total > 1: + result.append(0) + elif zero_total == 1: + if num == 0: + result.append(non_zero_product) + else: + result.append(raw_product) + else: + result.append(raw_product // num) + + return result From c184b940499b6c893222a5e25254847b52b2fee4 Mon Sep 17 00:00:00 2001 From: jinah92 Date: Fri, 27 Dec 2024 11:53:24 +0900 Subject: [PATCH 099/183] =?UTF-8?q?feat:=20week3=20medium=20=EB=AC=B8?= =?UTF-8?q?=EC=A0=9C=ED=92=80=EC=9D=B4(combination-sum)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- combination-sum/jinah92.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 combination-sum/jinah92.py diff --git a/combination-sum/jinah92.py b/combination-sum/jinah92.py new file mode 100644 index 000000000..ba0500ba0 --- /dev/null +++ b/combination-sum/jinah92.py @@ -0,0 +1,19 @@ +# O(T) time, O(C^T) space +class Solution: + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + results, nums = [], [] + + def dfs(start, total): + if total > target: + return + if total == target: + results.append(nums[:]) + for i in range(start, len(candidates)): + num = candidates[i] + nums.append(num) + dfs(i, total + num) + nums.pop() + + dfs(0, 0) + + return results From 58d4dd300f4c1fb784d1c558a2676ce5ac273891 Mon Sep 17 00:00:00 2001 From: Nayeon Date: Fri, 27 Dec 2024 14:39:21 +0900 Subject: [PATCH 100/183] Add solution for "234. Reverse Bits" --- reverse-bits/KwonNayeon.py | 24 ++++++++++++++++++++++++ two-sum/KwonNayeon.py | 6 ++---- 2 files changed, 26 insertions(+), 4 deletions(-) create mode 100644 reverse-bits/KwonNayeon.py diff --git a/reverse-bits/KwonNayeon.py b/reverse-bits/KwonNayeon.py new file mode 100644 index 000000000..838ff907d --- /dev/null +++ b/reverse-bits/KwonNayeon.py @@ -0,0 +1,24 @@ +""" +Constraints: + - The input must be a binary string of length 32 + +Time Complexity: O(1) + - 항상 고정된 32비트 문자열에 대해 연산하므로 상수 시간 + +Space Complexity: O(1) + - 32비트 고정 크기의 문자열 연산만 사용하므로 상수 공간 + +풀이 방법: + 1. format(n, '032b')를 사용해 입력받은 정수를 32비트 이진수 문자열로 변환함 + 2. 문자열 슬라이싱 [::-1]으로 비트를 뒤집음 + 3. int(reversed_binary, 2)로 뒤집은 이진수 문자열을 다시 정수로 변환함 +""" + +class Solution: + def reverseBits(self, n: int) -> int: + + binary = format(n, '032b') + + reversed_binary = binary[::-1] + + return int(reversed_binary, 2) diff --git a/two-sum/KwonNayeon.py b/two-sum/KwonNayeon.py index 209596b1a..969e83b72 100644 --- a/two-sum/KwonNayeon.py +++ b/two-sum/KwonNayeon.py @@ -5,13 +5,13 @@ - -10^9 <= target <= 10^9 - Only one valid answer exists. - Time Complexity: O(n²) +Time Complexity: O(n²) - 중첩 반복문을 사용하기 때문 - 첫 번째 반복문: n번 - 각각에 대해 두 번째 반복문: n-1, n-2, ... 1번 - 따라서 총 연산 횟수는 n * (n-1)/2로 O(n²) - Space Complexity: O(1) +Space Complexity: O(1) - 추가 공간을 사용하지 않음 - result 리스트는 항상 크기가 2로 고정 """ @@ -23,5 +23,3 @@ def twoSum(self, nums: List[int], target: int) -> List[int]: for j in range(i+1, len(nums)): if nums[j] == target - nums[i]: return [i, j] - - From 4bf596efa4a1c3deeea6600690bfb48cf3da2924 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=8B=E1=85=B5=E1=84=8B=E1=85=A7=E1=86=AB=E1=84=89?= =?UTF-8?q?=E1=85=AE?= Date: Fri, 27 Dec 2024 17:24:38 +0900 Subject: [PATCH 101/183] two sum --- two-sum/EcoFriendlyAppleSu.kt | 42 +++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 two-sum/EcoFriendlyAppleSu.kt diff --git a/two-sum/EcoFriendlyAppleSu.kt b/two-sum/EcoFriendlyAppleSu.kt new file mode 100644 index 000000000..d980e8428 --- /dev/null +++ b/two-sum/EcoFriendlyAppleSu.kt @@ -0,0 +1,42 @@ +package leetcode_study + +/** + * 주어진 숫자 배열에서 두 개의 숫자를 더해 Target을 만들 수 있는 배열의 Index를 구하는 문제 + * 조합을 사용해 문제 해결 + * 시간 복잡도: O(n^2) + * -> 두 번의 순회를 통해 모든 경우의 수를 계산하는 경우 + * 공간 복잡도: O(1) + * -> 결과를 저장하는 result, 배열의 index를 가리키는 indices는 두 개의 값을 담기 때문에 O(1) + */ +fun twoSum(nums: IntArray, target: Int): IntArray { + val result = IntArray(2) + val k = 2 + val maxSize = nums.size + val indices = IntArray(k) + for (i in 0 until k ) { + indices[i] = i + } + + while (indices[k-1] < maxSize) { + if (nums[indices[0]] + nums[indices[1]] == target) { + result[0] = indices[0] + result[1] = indices[1] + return result + } + + var i = k - 1 + while (i >= 0 && indices[i] == i + maxSize - k) { + i-- + } + + if (i >= 0) { + indices[i]++ + for (j in i + 1 until k) { + indices[j] = indices[j - 1] + 1 + } + } else { + break + } + } + return result +} From 93fe9c34f4a4307016652e24c9145c6a93700473 Mon Sep 17 00:00:00 2001 From: jinah92 Date: Fri, 27 Dec 2024 17:27:56 +0900 Subject: [PATCH 102/183] =?UTF-8?q?feat:=20week3=20medium=20=EB=AC=B8?= =?UTF-8?q?=EC=A0=9C=ED=92=80=EC=9D=B4(maximum-subarray)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- maximum-subarray/jinah92.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 maximum-subarray/jinah92.py diff --git a/maximum-subarray/jinah92.py b/maximum-subarray/jinah92.py new file mode 100644 index 000000000..dcf0d88b5 --- /dev/null +++ b/maximum-subarray/jinah92.py @@ -0,0 +1,14 @@ +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + num_set = {} + result = -math.inf + + for idx, num in enumerate(nums): + if idx == 0: + num_set[idx] = max(nums[0], result) + else: + num_set[idx] = max(num, num_set[idx-1] + num) + tmp_sum = num_set[idx] + result = max(result, tmp_sum) + + return result From f4a56839f4e2bcd92a3e85aaede49f84e176cc33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EC=9D=80=EB=B9=88=20Eunbeen=20Kang?= <145640625+river20s@users.noreply.github.com> Date: Fri, 27 Dec 2024 18:25:32 +0900 Subject: [PATCH 103/183] solution reverse bits --- reverse-bits/river20s.java | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 reverse-bits/river20s.java diff --git a/reverse-bits/river20s.java b/reverse-bits/river20s.java new file mode 100644 index 000000000..76a976fe9 --- /dev/null +++ b/reverse-bits/river20s.java @@ -0,0 +1,22 @@ +public class Solution { + /* T.C = O(1) + * S.C = O(1) + */ + public int reverseBits(int n) { + // Set the output to 0 + int output = 0; + // Repeat 32 times + for (int i = 0; i < 32; i++) { + // Shift the output value one space to the left to make room for the new bit + output <<= 1; + // '&' operation to get the rightmost bit and add it to the output + output = output | (n & 1); + // Discard the rightmost bit of the 'n' + n = n >> 1; + } + + return output; + + } +} + From cd96d8bb984fd75da74e40931c3ae1f9303b1ffc Mon Sep 17 00:00:00 2001 From: GangBean Date: Fri, 27 Dec 2024 19:53:11 +0900 Subject: [PATCH 104/183] feat: solve combination sum --- combination-sum/GangBean.java | 43 +++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 combination-sum/GangBean.java diff --git a/combination-sum/GangBean.java b/combination-sum/GangBean.java new file mode 100644 index 000000000..04d9b46c1 --- /dev/null +++ b/combination-sum/GangBean.java @@ -0,0 +1,43 @@ +class Solution { + public List> combinationSum(int[] candidates, int target) { + /** + 1. understanding + - find all combinations, which sum to target + - can use same number multiple times + 2. strategy + - dp[target]: all combination, which sum to target + - dp[n + 1] = dp[n] | dp[1] + - [2,3,6,7], target = 7 + - dp[0] = [[]] + - dp[1] = [[]] + - dp[2] = [[2]] + - dp[3] = [[3]] + - dp[4] = dp[2] | dp[2] = [[2,2]] + - dp[5] = dp[2] | dp[3] = [[2,3]] + - dp[6] = dp[2] | dp[4] , dp[3] | dp[3] = [[2,2,2], [3,3]] + - dp[7] = dp[2] | dp[5], dp[3] | dp[4], dp[6] | dp[1], dp[7] = [[2,2,3],] + 3. complexity + - time: O(target * N) where N is length of candidates + - space: O(target * N) + */ + List>[] dp = new List[target + 1]; + for (int i = 0; i <= target; i++) { + dp[i] = new ArrayList<>(); + } + + dp[0].add(new ArrayList<>()); + + for (int candidate : candidates) { + for (int i = candidate; i <= target; i++) { + for (List combination : dp[i - candidate]) { + List newCombination = new ArrayList<>(combination); + newCombination.add(candidate); + dp[i].add(newCombination); + } + } + } + + return dp[target]; + } +} + From 547b2dc1149c55441bfbca90b11fbb61b37691e0 Mon Sep 17 00:00:00 2001 From: dongha kim Date: Fri, 27 Dec 2024 21:04:05 +0900 Subject: [PATCH 105/183] feat : week 3 --- combination-sum/imsosleepy.java | 26 +++++++++ maximum-subarray/imsosleepy.java | 16 ++++++ product-of-array-except-self/imssoleepy.java | 20 +++++++ reverse-bits/imsosleepy.java | 23 ++++++++ two-sum/imsosleepy.java | 59 ++++++++++++++++++++ 5 files changed, 144 insertions(+) create mode 100644 combination-sum/imsosleepy.java create mode 100644 maximum-subarray/imsosleepy.java create mode 100644 product-of-array-except-self/imssoleepy.java create mode 100644 reverse-bits/imsosleepy.java create mode 100644 two-sum/imsosleepy.java diff --git a/combination-sum/imsosleepy.java b/combination-sum/imsosleepy.java new file mode 100644 index 000000000..399f0a182 --- /dev/null +++ b/combination-sum/imsosleepy.java @@ -0,0 +1,26 @@ +// 처음엔 dp라 생각했는데, backtracking인걸 알아차리자마자 풀 수 있었음 +// 중간 결과를 계속 전달하는게 팁 +class Solution { + public List> combinationSum(int[] candidates, int target) { + List> result = new ArrayList<>(); + backtracking(candidates, target, 0, new ArrayList<>(), result); + return result; + } + + private void backtracking(int[] candidates, int target, int start, List tmp, List> result) { + if (target < 0) { + return; + } + + if (target == 0) { + result.add(new ArrayList<>(tmp)); + return; + } + + for (int i = start; i < candidates.length; i++) { + tmp.add(candidates[i]); + backtracking(candidates, target - candidates[i], i, tmp, result); + tmp.remove(tmp.size() - 1); + } + } +} diff --git a/maximum-subarray/imsosleepy.java b/maximum-subarray/imsosleepy.java new file mode 100644 index 000000000..a6d977b22 --- /dev/null +++ b/maximum-subarray/imsosleepy.java @@ -0,0 +1,16 @@ +// subarray = "연속된 값"의 합을 요구 함 그래서 간단한 풀이가 가능하다. +// 이전 인덱스나 값들을 기억할 필요가 없어서 누적합 느낌으로 풀 수 있다. +// 키포인트는 이전까지의 합보다 다음 숫자가 큰 경우의 수가 존재한다는 것 +class Solution { + public int maxSubArray(int[] nums) { + int max = nums[0]; + int current = nums[0]; + + for (int i = 1; i < nums.length; i++) { + current = Math.max(nums[i], current + nums[i]); + max = Math.max(max, current); + } + + return max; + } +} diff --git a/product-of-array-except-self/imssoleepy.java b/product-of-array-except-self/imssoleepy.java new file mode 100644 index 000000000..9b7edc0f6 --- /dev/null +++ b/product-of-array-except-self/imssoleepy.java @@ -0,0 +1,20 @@ +class Solution { + // 누적곱을 이용한 풀이 int 크기를 보장해줘서 int를 사용하면된다. + // O(N)의 시간복잡도가 나온다. + public int[] productExceptSelf(int[] nums) { + int n = nums.length; + int[] result = new int[n]; + result[0] = 1; + for (int i = 1; i < n; i++) { + result[i] = result[i - 1] * nums[i - 1]; + } + + int right = 1; + for (int i = n - 1; i >= 0; i--) { + result[i] = result[i] * right; + right *= nums[i]; + } + + return result; + } +} diff --git a/reverse-bits/imsosleepy.java b/reverse-bits/imsosleepy.java new file mode 100644 index 000000000..38f272bb5 --- /dev/null +++ b/reverse-bits/imsosleepy.java @@ -0,0 +1,23 @@ +// 스택으로 풀기보다 비트연산자로 풀이 +// 스택을 사용할 때는 32자리의 불필요한 공간이 생긴다. +public class Solution { + public int reverseBits(int n) { + // n 이 십진수로 들어온다.(중요) + int result = 0; + for (int i = 0; i < 32; i++) { + // 마지막 비트 확인 + // 홀수: 마지막 비트가 1 (n & 1 == 1) + // 짝수: 마지막 비트가 0 (n & 1 == 0) + int bit = n & 1; + // result를 왼쪽으로 1비트 이동하고, 추출한 비트를 추가 + // - result의 마지막 비트를 비우고 (<< 1) + // - OR 연산(|)으로 추출한 비트를 추가 + result = (result << 1) | bit; + + // n을 오른쪽으로 1비트 이동하여 다음 비트를 준비 + // - n의 마지막 비트를 버리고, 상위 비트를 아래로 이동 + n >>= 1; + } + return result; + } +} diff --git a/two-sum/imsosleepy.java b/two-sum/imsosleepy.java new file mode 100644 index 000000000..7ff6f1019 --- /dev/null +++ b/two-sum/imsosleepy.java @@ -0,0 +1,59 @@ +// hashmap 조회 방식은 O(N) +// 3ms +public int[] twoSum(int[] nums, int target) { + Map map = new HashMap<>(); + for (int i = 0; i < nums.length; i++) { + int complement = target - nums[i]; + if (map.containsKey(complement)) { + return new int[] { map.get(complement), i }; + } + map.put(nums[i], i); + } + return null; +} + +// 첫 생각 : 정렬 -> 투포인터 +public int[] twoSum1(int[] nums, int target) { + Arrays.sort(nums); + int left = 0; + int right = nums.length-1; + int sum = 0; + while(left < right) { + sum = nums[left] + nums[right]; + if(target > sum) { + left++; + } + if(target < sum) { + right--; + } + if(target == sum) { + break; + } + } + return new int[]{left, right}; +} + +// 투포인터는 O(N)에 충족하지만 정렬이 nlog(n)임 +// 9ms +public int[] twoSum2(int[] nums, int target) { + int[][] indexedNums = new int[nums.length][2]; + for (int i = 0; i < nums.length; i++) { + indexedNums[i][0] = nums[i]; + indexedNums[i][1] = i; + } + + Arrays.sort(indexedNums, Comparator.comparingInt(a -> a[0])); + + int left = 0, right = nums.length - 1; + while (left < right) { + int sum = indexedNums[left][0] + indexedNums[right][0]; + if (sum == target) { + return new int[] { indexedNums[left][1], indexedNums[right][1] }; + } else if (sum < target) { + left++; + } else { + right--; + } + } + return new int[]{left, right}; +} From 08a41dd2f29be67f1f7f5ba34e96e633dfae7c88 Mon Sep 17 00:00:00 2001 From: dongha kim Date: Fri, 27 Dec 2024 21:14:52 +0900 Subject: [PATCH 106/183] =?UTF-8?q?fix=20:=20=EB=A6=B0=ED=8A=B8=20?= =?UTF-8?q?=EC=98=A4=EB=A5=98=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- product-of-array-except-self/{imssoleepy.java => imsosleepy.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename product-of-array-except-self/{imssoleepy.java => imsosleepy.java} (100%) diff --git a/product-of-array-except-self/imssoleepy.java b/product-of-array-except-self/imsosleepy.java similarity index 100% rename from product-of-array-except-self/imssoleepy.java rename to product-of-array-except-self/imsosleepy.java From 15eca17efeed9de9ad5cd18727e50b7ebe49f123 Mon Sep 17 00:00:00 2001 From: Nayeon Date: Fri, 27 Dec 2024 21:29:32 +0900 Subject: [PATCH 107/183] Solved "239. Product of Array Except Self" --- product-of-array-except-self/KwonNayeon.py | 38 ++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 product-of-array-except-self/KwonNayeon.py diff --git a/product-of-array-except-self/KwonNayeon.py b/product-of-array-except-self/KwonNayeon.py new file mode 100644 index 000000000..1ac91388e --- /dev/null +++ b/product-of-array-except-self/KwonNayeon.py @@ -0,0 +1,38 @@ +""" +Constraints: + 1. 2 <= nums.length <= 10^5 + 2. -30 <= nums[i] <= 30 + 3. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer + +Time Complexity: O(n) + - 배열을 두 번 순회하므로 O(n) + +Space Complexity: O(1) + - 출력 배열(answer)을 제외하면 추가 공간이 상수만큼만 필요(left, right 변수) + +풀이 방법: + 1. answer 배열을 1로 초기화 (곱셈에서는 1이 영향을 주지 않음) + 2. 왼쪽에서 오른쪽으로 순회: + - answer[i]에 현재까지의 left 누적값을 곱함 + - left *= nums[i]로 다음을 위해 left 값을 업데이트 + 3. 오른쪽에서 왼쪽으로 순회 (range(n-1, -1, -1) 사용): + - answer[i]에 현재까지의 right 누적값을 곱함 + - right *= nums[i]로 다음을 위해 right 값을 업데이트 +""" + +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + n = len(nums) + answer = [1] * n + + left = 1 + for i in range(n): + answer[i] *= left + left *= nums[i] + + right = 1 + for i in range(n-1, -1, -1): + answer[i] *= right + right *= nums[i] + + return answer From d4b4783a9b17538e8c7375a97f28b8ee9f18157e Mon Sep 17 00:00:00 2001 From: Heejin Ham Date: Fri, 27 Dec 2024 21:45:55 +0900 Subject: [PATCH 108/183] [Week3](gmlwls96) Maximum-subarray --- maximum-subarray/gmlwls96.kt | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 maximum-subarray/gmlwls96.kt diff --git a/maximum-subarray/gmlwls96.kt b/maximum-subarray/gmlwls96.kt new file mode 100644 index 000000000..552d391f1 --- /dev/null +++ b/maximum-subarray/gmlwls96.kt @@ -0,0 +1,22 @@ +class Solution { + fun maxSubArray(nums: IntArray): Int { + val dp = Array(nums.size) { y -> + IntArray(nums.size) { x -> + if (y == x) { + nums[y] + } else { + 0 + } + } + } + + var max = dp[0][0] + for (y in nums.indices) { + for (x in y + 1..nums.lastIndex) { + dp[y][x] = dp[y][x - 1] + nums[x] + max = max(max, dp[y][x]) + } + } + return max + } +} From 9c1fff6094d261daaafa6e6750bdf7888517d559 Mon Sep 17 00:00:00 2001 From: forest000014 Date: Fri, 27 Dec 2024 21:46:06 +0900 Subject: [PATCH 109/183] Maximum Subarray --- maximum-subarray/forest000014.java | 38 ++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 maximum-subarray/forest000014.java diff --git a/maximum-subarray/forest000014.java b/maximum-subarray/forest000014.java new file mode 100644 index 000000000..538195074 --- /dev/null +++ b/maximum-subarray/forest000014.java @@ -0,0 +1,38 @@ +/* +time complexity: O(n) +space complexity: O(1) + +왼쪽에서부터 누적합을 구하되, 더한 값이 음수가 되는 순간 지금까지 더한 값을 버린다. (즉, 지금까지의 원소는 모두 subarray에서 제외한다.) 이렇게 누적합을 계산하면서, 누적합의 최대값을 찾으면 답이 된다. + +단, 모든 원소가 음수인 경우는 예외적으로 처리해준다. + +*/ + +class Solution { + public int maxSubArray(int[] nums) { + int n = nums.length; + int ans = -10001; + int max = -10001; + int sum = 0; + for (int i = 0; i < n; i++) { + if (sum + nums[i] < 0) { + sum = 0; + } else { + sum += nums[i]; + } + if (sum > ans) { + ans = sum; + } + if (max < nums[i]) { + max = nums[i]; + } + } + + // 모두 음수인 경우의 예외 처리 + if (max < 0) { + return max; + } else { + return ans; + } + } +} From a1487757651eb9ee9a4698fd5772069a1d2d47a5 Mon Sep 17 00:00:00 2001 From: hyerin Date: Fri, 27 Dec 2024 22:29:44 +0900 Subject: [PATCH 110/183] add: two-sum --- two-sum/HerrineKim.js | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 two-sum/HerrineKim.js diff --git a/two-sum/HerrineKim.js b/two-sum/HerrineKim.js new file mode 100644 index 000000000..595c2898b --- /dev/null +++ b/two-sum/HerrineKim.js @@ -0,0 +1,22 @@ +// 시간 복잡도 : O(n) +// 공간 복잡도 : O(n) + +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var twoSum = function(nums, target) { + let numMap = new Map(); + + for (let i = 0; i < nums.length; i++) { + let complement = target - nums[i]; + + if (numMap.has(complement)) { + return [numMap.get(complement), i]; + } + + numMap.set(nums[i], i); + } +}; + From b7f8de25d3d9b9c2787339617ba563583b451755 Mon Sep 17 00:00:00 2001 From: donghyeon95 Date: Fri, 27 Dec 2024 22:38:26 +0900 Subject: [PATCH 111/183] feat: Two Sum #219 --- two-sum/donghyeon95.java | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 two-sum/donghyeon95.java diff --git a/two-sum/donghyeon95.java b/two-sum/donghyeon95.java new file mode 100644 index 000000000..8f72e6b5c --- /dev/null +++ b/two-sum/donghyeon95.java @@ -0,0 +1,31 @@ +import java.util.HashMap; +import java.util.HashSet; + +class Solution { + public int[] twoSum(int[] nums, int target) { + // // O(N^2) + // for (int i =0; i< nums.length-1; i++) { + // for (int j=i+1; j map = new HashMap<>(); + for (int i=0; i Date: Fri, 27 Dec 2024 23:02:38 +0900 Subject: [PATCH 112/183] add: maximum-subarray --- maximum-subarray/HerrineKim.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 maximum-subarray/HerrineKim.js diff --git a/maximum-subarray/HerrineKim.js b/maximum-subarray/HerrineKim.js new file mode 100644 index 000000000..87ed8199c --- /dev/null +++ b/maximum-subarray/HerrineKim.js @@ -0,0 +1,18 @@ +// 시간 복잡도 : O(n) +// 공간 복잡도 : O(1) + +/** + * @param {number[]} nums + * @return {number} + */ +var maxSubArray = function(nums) { + let currentSum = nums[0]; + let maxSum = nums[0]; + + for (let i = 1; i < nums.length; i++) { + currentSum = Math.max(nums[i], currentSum + nums[i]); + maxSum = Math.max(maxSum, currentSum); + } + + return maxSum; +}; From 87ddbc11040a667649394b600a2a7a371b7c359d Mon Sep 17 00:00:00 2001 From: limlim Date: Fri, 27 Dec 2024 23:17:33 +0900 Subject: [PATCH 113/183] product of array except self solution --- product-of-array-except-self/limlimjo.js | 27 ++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 product-of-array-except-self/limlimjo.js diff --git a/product-of-array-except-self/limlimjo.js b/product-of-array-except-self/limlimjo.js new file mode 100644 index 000000000..8e8d7f806 --- /dev/null +++ b/product-of-array-except-self/limlimjo.js @@ -0,0 +1,27 @@ +/** + * @param {number[]} nums + * @return {number[]} + */ +var productExceptSelf = function (nums) { + const result = new Array(nums.length).fill(1); // 결과값 + + // 왼쪽 곱 계산 + let leftProduct = 1; + for (let i = 0; i < nums.length; i++) { + result[i] = leftProduct; + leftProduct *= nums[i]; + } + + // 오른쪽 곱 계산해서 왼쪽 곱 계산한거 곱해주기 + let rightProduct = 1; + for (let i = nums.length - 1; i >= 0; i--) { + result[i] *= rightProduct; + rightProduct *= nums[i]; + } + + return result; +}; + +// 조건에 O(n)이라고 있음 +// 시간 복잡도: O(n) +// 공간 복잡도: O(n) From ba84e6d032fb8bc938e3dc682ffc8d35d2ed4afd Mon Sep 17 00:00:00 2001 From: aa601 Date: Fri, 27 Dec 2024 23:19:34 +0900 Subject: [PATCH 114/183] feat : solved 2sum, reverse_bits, product_of_array --- product-of-array-except-self/aa601.py | 17 +++++++++++++++++ reverse-bits/aa601.py | 10 ++++++++++ two-sum/aa601.py | 9 +++++++++ 3 files changed, 36 insertions(+) create mode 100644 product-of-array-except-self/aa601.py create mode 100644 reverse-bits/aa601.py create mode 100644 two-sum/aa601.py diff --git a/product-of-array-except-self/aa601.py b/product-of-array-except-self/aa601.py new file mode 100644 index 000000000..cfd7ab4d9 --- /dev/null +++ b/product-of-array-except-self/aa601.py @@ -0,0 +1,17 @@ +#시간복잡도: O(n), 공간복잡도 : O(n) + +class Solution: + def productExceptSelf(self, nums: list[int]) -> list[int] : + a = [1] * len(nums) + for n in range(len(nums) - 1) : + a[n + 1] = a[n] * nums[n] + + b = [1] * len(nums) + for n in range(len(nums) - 1, 0, -1) : + b[n - 1] = b[n] * nums[n] + + c = [1] * len(nums) + for n in range(len(nums)) : + c[n] = a[n] * b[n] + return c + diff --git a/reverse-bits/aa601.py b/reverse-bits/aa601.py new file mode 100644 index 000000000..adb619f25 --- /dev/null +++ b/reverse-bits/aa601.py @@ -0,0 +1,10 @@ +#시간복잡도 : O(1), 공간복잡도 : O(1) + +class Solution: + def reverseBits(self, n: int) -> int: + ret = 0 + for i in range(32) : + ret = (ret << 1 | (n & 1)) + n >>= 1 + return (ret) + diff --git a/two-sum/aa601.py b/two-sum/aa601.py new file mode 100644 index 000000000..d5e9875d6 --- /dev/null +++ b/two-sum/aa601.py @@ -0,0 +1,9 @@ +#시간복잡도 : O(n^2), 공간복잡도 : O(1) + +class Solution: + def twoSum(self, nums: list[int], target: int) -> list[int]: + for i in range(len(nums) - 1): + for k in range(i + 1, len(nums)): + if (nums[i] + nums[k] == target): + return ([i, k]) + From 23966d57e7d4e44aa9815ef3445f5d3f1e720009 Mon Sep 17 00:00:00 2001 From: Dusuna <94776135+dusunax@users.noreply.github.com> Date: Fri, 27 Dec 2024 23:52:33 +0900 Subject: [PATCH 115/183] add solution: combination-sum --- combination-sum/dusunax.py | 39 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 combination-sum/dusunax.py diff --git a/combination-sum/dusunax.py b/combination-sum/dusunax.py new file mode 100644 index 000000000..9126e5924 --- /dev/null +++ b/combination-sum/dusunax.py @@ -0,0 +1,39 @@ +''' +# 39. Combination Sum + +Backtracking for find combinations. + +## Time and Space Complexity + +``` +TC: O(n^2) +SC: O(n) +``` + +#### TC is O(n^2): +- iterating through the list in backtracking recursion to find combinations. = O(n^2) + +#### SC is O(n): +- using a list to store the combinations. = O(n) +''' + +class Solution: + # Backtracking = find combination + # candidate is distinct & can use multiple times. + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + result = [] + + def backtrack(currIdx, remain, combination): + if(remain == 0): + result.append(combination[:]) + return + if(remain < 0): + return + + for i in range(currIdx, len(candidates)): + combination.append(candidates[i]) + backtrack(i, remain - candidates[i], combination) + combination.pop() + + backtrack(0, target, [permutations]) + return result From 3427d402e01b9443e294cac6c2f224c42a8eb1bb Mon Sep 17 00:00:00 2001 From: nakjun <111031253+nakjun12@users.noreply.github.com> Date: Sat, 28 Dec 2024 00:12:29 +0900 Subject: [PATCH 116/183] add two-sum solution --- two-sum/nakjun12.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 two-sum/nakjun12.ts diff --git a/two-sum/nakjun12.ts b/two-sum/nakjun12.ts new file mode 100644 index 000000000..8c1ac2570 --- /dev/null +++ b/two-sum/nakjun12.ts @@ -0,0 +1,20 @@ +/* + * TC: O(n) + * SC: O(n) + * */ +function twoSum(nums: number[], target: number): number[] { + const indices = {}; + + for (let i = 0; i < nums.length; i++) { + const curNum = nums[i]; + const complement = target - curNum; + + if (complement in indices) { + return [indices[complement], i]; + } + + indices[curNum] = i; + } + + return []; +} From fc875c4ae19185b3eed9a400f3dd46e6c1b94dce Mon Sep 17 00:00:00 2001 From: donghyeon95 Date: Sat, 28 Dec 2024 00:14:59 +0900 Subject: [PATCH 117/183] feat:Reverse Bits #234 --- reverse-bits/donghyeon95.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 reverse-bits/donghyeon95.java diff --git a/reverse-bits/donghyeon95.java b/reverse-bits/donghyeon95.java new file mode 100644 index 000000000..41c84f513 --- /dev/null +++ b/reverse-bits/donghyeon95.java @@ -0,0 +1,16 @@ +public class Solution { + // you need treat n as an unsigned value + public int reverseBits(int n) { + int result = 0; + + for (int i = 0; i < 32; i++) { + // 왼쪽으로 비트를 한 칸 이동하고, n의 마지막 비트를 추가 + result = (result << 1) | (n & 1); + // n을 오른쪽으로 한 칸 이동 + n >>= 1; + } + + return result; + } +} + From ea9aa53c075ec301af070c578ca4aa7b6a9982e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=8B=E1=85=B5=E1=84=8B=E1=85=A7=E1=86=AB=E1=84=89?= =?UTF-8?q?=E1=85=AE?= Date: Sat, 28 Dec 2024 00:17:09 +0900 Subject: [PATCH 118/183] reverse bits --- reverse-bits/EcoFriendlyAppleSu.kt | 50 ++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 reverse-bits/EcoFriendlyAppleSu.kt diff --git a/reverse-bits/EcoFriendlyAppleSu.kt b/reverse-bits/EcoFriendlyAppleSu.kt new file mode 100644 index 000000000..0e0a45dc0 --- /dev/null +++ b/reverse-bits/EcoFriendlyAppleSu.kt @@ -0,0 +1,50 @@ +package leetcode_study + +/* +* 주어진 32 bits unsigned integer를 뒤집는 문제 +* Bit 연산에 대한 개념이 전무해 String으로 치환 후 문제 해결 +* 작은 수는 표현할 수 있었지만 아래와 같이 문제를 해결할 경우 큰 수가 입력되었을 경우 부호 비트를 인식하여 음수로 표기합니다. +* 또한 32 bit를 구성하기 위해 부족한 문자열을(자릿수) 추가하기 때문에 연산이 더해집니다. +* */ +fun reverseBits1(n:Int):Int { + val nStr = n.toString(2) + val totalLength = nStr.length + var temp = "" + if (totalLength != 32) { + for (i in 0 until 32 - totalLength) { + temp += "0" + } + } + val fullBitString = temp + nStr + var result = 0 + + for (i in (fullBitString.length - 1) downTo 0) { + val eachBitValue = 2.0.pow(i).toInt() + if (fullBitString[i] == '0') { + continue + } else { + result += eachBitValue + } + } + println(result.toString(2)) + return result +} + +/* +* Bit 연산을 통한 Reverse Bit 구성 +* 시간 복잡도: O(32) (32비트의 숫자에 대해 반복) +* 공간 복잡도: O(1) (상수 공간 사용) +* */ +fun reverseBits(n: Int): Int { + var input = n + var result = 0 + + for (i in 0 until 32) { + // 결과에 현재 비트 추가 + result = (result shl 1) or (input and 1) + // 입력 비트를 오른쪽으로 이동 + input = input shr 1 + } + + return result +} From e1d144dc6b47c3f861bd431a18a7e59f7e840b0b Mon Sep 17 00:00:00 2001 From: Youngjae Kim Date: Sat, 28 Dec 2024 00:56:44 +0900 Subject: [PATCH 119/183] add: solve #239 Product of Array Except Self with ts --- product-of-array-except-self/Yjason-K.ts | 38 ++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 product-of-array-except-self/Yjason-K.ts diff --git a/product-of-array-except-self/Yjason-K.ts b/product-of-array-except-self/Yjason-K.ts new file mode 100644 index 000000000..50f99518d --- /dev/null +++ b/product-of-array-except-self/Yjason-K.ts @@ -0,0 +1,38 @@ +/** + * 주어진 배열에서 자신의 인덱스를 제외한 나머지 요소들의 곱을 계산하는 함수 + * + * @param {number[]} nums - 정수 배열 + * @returns {number[]} - 각 인덱스의 요소를 제외한 나머지 요소들의 곱을 구한 배열 + * + * 1. 결과 배열 `result`를 1로 초기화. + * 2. 왼쪽에서 오른쪽으로 순회하며 `left` 값을 이용해 기준 idx 이전의 값을 계산하여 `result`에 저장. + * 3. 오른쪽에서 왼쪽으로 순회하며 `right` 값을 이용해 접미 기준 idx 이후의 값들을 계산 히야 `result`에 곱함. + * 4. 결과 배열 `result`를 반환. + * + * 시간 복잡도: + * - 왼쪽에서 오른쪽 순회: O(n) + * - 오른쪽에서 왼쪽 순회: O(n) + * - 전체 시간 복잡도: O(n) + * + * 공간 복잡도: + * - 추가 배열 없이 상수 공간 사용 (result는 문제의 요구 조건에 포함되지 않음). + * - 전체 공간 복잡도: O(1) + */ +function productExceptSelf(nums: number[]): number[] { + const numLength = nums.length; + const result = new Array(numLength).fill(1); + + let left = 1; + for (let i = 0; i < numLength; i++) { + result[i] *= left; + left *= nums[i]; + } + + let right = 1; + for (let i = numLength; i >= 0; i--) { + result[i] *= right; + right *= nums[i]; + } + + return result; +} From a2ac1b08dd0446c3ef1434936c073b50cae8451c Mon Sep 17 00:00:00 2001 From: Youngjae Kim Date: Sat, 28 Dec 2024 01:00:58 +0900 Subject: [PATCH 120/183] fix: #241 line break fixed --- 3sum/Yjason-K.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/3sum/Yjason-K.ts b/3sum/Yjason-K.ts index ad481c049..1ee84ae66 100644 --- a/3sum/Yjason-K.ts +++ b/3sum/Yjason-K.ts @@ -49,4 +49,5 @@ function threeSum(nums: number[]): number[][] { } return result; -} \ No newline at end of file +} + From 1d20733d0344f9f1ad37d1d107972fa60ec247d0 Mon Sep 17 00:00:00 2001 From: Dal_Peng Date: Sat, 28 Dec 2024 01:02:40 +0900 Subject: [PATCH 121/183] :art: reverse bits, product of array except self Solution --- product-of-array-except-self/dalpang81.java | 23 +++++++++++++++++++++ reverse-bits/dalpang81.java | 16 ++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 product-of-array-except-self/dalpang81.java create mode 100644 reverse-bits/dalpang81.java diff --git a/product-of-array-except-self/dalpang81.java b/product-of-array-except-self/dalpang81.java new file mode 100644 index 000000000..9960f0570 --- /dev/null +++ b/product-of-array-except-self/dalpang81.java @@ -0,0 +1,23 @@ +/* +* 시간복잡도: O(n) +* 공간복잡도: O(1) +* */ +class Solution { + public int[] productExceptSelf(int[] nums) { + int n = nums.length; + int[] answer = new int[n]; + + answer[0] = 1; + for (int i = 1; i < n; i++) { + answer[i] = answer[i - 1] * nums[i - 1]; + } + + int suffixProduct = 1; + for (int i = n - 1; i >= 0; i--) { + answer[i] *= suffixProduct; + suffixProduct *= nums[i]; + } + + return answer; + } +} diff --git a/reverse-bits/dalpang81.java b/reverse-bits/dalpang81.java new file mode 100644 index 000000000..99050b039 --- /dev/null +++ b/reverse-bits/dalpang81.java @@ -0,0 +1,16 @@ +/* +* 시간복잡도: O(1) +* 공간복잡도: O(1) +* */ +public class Solution { + // you need treat n as an unsigned value + public int reverseBits(int n) { + int result = 0; + for (int i = 0; i < 32; i++) { + result <<= 1; + result |= (n & 1); + n >>= 1; + } + return result; + } +} From 43b2831c9c0c9ccd58f62496d1e62f5f7d17d27e Mon Sep 17 00:00:00 2001 From: hyerin Date: Sat, 28 Dec 2024 01:23:02 +0900 Subject: [PATCH 122/183] add: combination-sum --- combination-sum/HerrineKim.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 combination-sum/HerrineKim.js diff --git a/combination-sum/HerrineKim.js b/combination-sum/HerrineKim.js new file mode 100644 index 000000000..fa574a10e --- /dev/null +++ b/combination-sum/HerrineKim.js @@ -0,0 +1,30 @@ +// 시간 복잡도 : O(n^2) +// 공간 복잡도 : O(n) + +/** + * @param {number[]} candidates + * @param {number} target + * @return {number[][]} + */ + +var combinationSum = function(candidates, target) { + const result = []; + + const backtrack = (remaining, combo, start) => { + if (remaining === 0) { + result.push([...combo]); + return; + } + + for (let i = start; i < candidates.length; i++) { + if (candidates[i] <= remaining) { + combo.push(candidates[i]); + backtrack(remaining - candidates[i], combo, i); + combo.pop(); + } + } + }; + + backtrack(target, [], 0); + return result; +}; \ No newline at end of file From 3060e1e93c8c8cb9d345f7031e7badc5908d650e Mon Sep 17 00:00:00 2001 From: hyerin Date: Sat, 28 Dec 2024 01:23:50 +0900 Subject: [PATCH 123/183] fix: lint --- combination-sum/HerrineKim.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/combination-sum/HerrineKim.js b/combination-sum/HerrineKim.js index fa574a10e..4549f6f24 100644 --- a/combination-sum/HerrineKim.js +++ b/combination-sum/HerrineKim.js @@ -27,4 +27,4 @@ var combinationSum = function(candidates, target) { backtrack(target, [], 0); return result; -}; \ No newline at end of file +}; From 5747260d7de8fa2a7f6915e21465e4a5775ec772 Mon Sep 17 00:00:00 2001 From: mintheon Date: Sat, 28 Dec 2024 02:38:32 +0900 Subject: [PATCH 124/183] reverse bits solved --- reverse-bits/mintheon.java | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 reverse-bits/mintheon.java diff --git a/reverse-bits/mintheon.java b/reverse-bits/mintheon.java new file mode 100644 index 000000000..f1c2ffcb7 --- /dev/null +++ b/reverse-bits/mintheon.java @@ -0,0 +1,24 @@ +public class Solution { + /** + 시간복잡도: O(1) -> 루프는 항상 32번 반복되기 때문 + 공간복잡도: O(1) + */ + + // you need treat n as an unsigned value + public int reverseBits(int n) { + int answer = 0; + int index = 31; + + while(n != 0) { + // n&1 : 마지막 비트를 추출 + // << : 0을 패딩처리 시켜서 상위 자리수로 올려버림 + answer += (n & 1) << index; + + // >>> : 부호 상관없이 오른쪽으로 비트 이동 + n = n >>> 1; + index--; + } + + return answer; + } +} From d6a33dd1ebc4520cb7b58774a7d950cc58235cb2 Mon Sep 17 00:00:00 2001 From: Dusuna <94776135+dusunax@users.noreply.github.com> Date: Sat, 28 Dec 2024 07:31:09 +0900 Subject: [PATCH 125/183] add solution: maximum-subarray --- maximum-subarray/dusunax.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 maximum-subarray/dusunax.py diff --git a/maximum-subarray/dusunax.py b/maximum-subarray/dusunax.py new file mode 100644 index 000000000..01022cdcc --- /dev/null +++ b/maximum-subarray/dusunax.py @@ -0,0 +1,34 @@ +''' +# 53. Maximum Subarray + +- use Kadane's Algorithm for efficiently finding the maximum subarray sum. + +## Time and Space Complexity + +``` +TC: O(n) +SC: O(1) +``` + +#### TC is O(n): +- iterating through the list just once to find the maximum subarray sum. = O(n) + +#### SC is O(1): +- using a constant amount of extra space to store the current sum and the maximum sum. = O(1) +''' + +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + if len(nums) == 1: + return nums[0] + + currentSum = 0 # SC: O(1) + maxSum = nums[0] # SC: O(1) + + for i in range(len(nums)): # TC: O(n) + currentSum = max(currentSum + nums[i], nums[i]) # TC: O(1) + + if currentSum > maxSum: # TC: O(1) + maxSum = currentSum + + return maxSum From 79f948bd9235605302d2a0bba9e8d09c0c9b0ab1 Mon Sep 17 00:00:00 2001 From: Paik Date: Sat, 28 Dec 2024 10:10:19 +0900 Subject: [PATCH 126/183] feat: 190. Reverse Bits --- reverse-bits/gwbaik9717.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 reverse-bits/gwbaik9717.js diff --git a/reverse-bits/gwbaik9717.js b/reverse-bits/gwbaik9717.js new file mode 100644 index 000000000..723e629df --- /dev/null +++ b/reverse-bits/gwbaik9717.js @@ -0,0 +1,25 @@ +// Time complexity: O(1) +// Space complexity: O(1) + +/** + * @param {number} n - a positive integer + * @return {number} - a positive integer + */ +var reverseBits = function (n) { + const stack = []; + let current = n; + + for (let i = 0; i < 32; i++) { + stack.push(current % 2); + current = Math.floor(current / 2); + } + + let answer = 0; + + for (let i = 0; i < 32; i++) { + const popped = stack.pop(); + answer += popped * 2 ** i; + } + + return answer; +}; From ce97ccebeb8bb3651bf8fe212bddc2aacc30831b Mon Sep 17 00:00:00 2001 From: Paik Date: Sat, 28 Dec 2024 10:40:38 +0900 Subject: [PATCH 127/183] feat: 238. Product of Array Except Self --- product-of-array-except-self/gwbaik9717.js | 33 ++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 product-of-array-except-self/gwbaik9717.js diff --git a/product-of-array-except-self/gwbaik9717.js b/product-of-array-except-self/gwbaik9717.js new file mode 100644 index 000000000..e779083ef --- /dev/null +++ b/product-of-array-except-self/gwbaik9717.js @@ -0,0 +1,33 @@ +// Time complexity: O(n) +// Space complexity: O(n) + +/** + * @param {number[]} nums + * @return {number[]} + */ +var productExceptSelf = function (nums) { + let count0 = 0; + + const totalProduct = nums.reduce((acc, num) => { + if (num === 0) { + count0++; + } + + return acc * num; + }, 1); + + return nums.map((num) => { + if (num === 0) { + // 0이 2 개 이상 존재할 때 + if (count0 > 1) { + return 0; + } + + // 0이 1 개 존재할 때 + // 0을 제외한 나머지 product 계산 (이 과정은 단 한번만 존재하기 때문에 시간 복잡도는 여전히 O(n)) + return nums.filter((num) => num !== 0).reduce((a, c) => a * c, 1); + } + + return totalProduct / num; + }); +}; From 912fe120c3605f13b87ee7b7c8059ecf5e0149fc Mon Sep 17 00:00:00 2001 From: mike2ox Date: Sat, 28 Dec 2024 12:40:25 +0900 Subject: [PATCH 128/183] feat: Upload two-sum(typescript) --- two-sum/mike2ox.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 two-sum/mike2ox.ts diff --git a/two-sum/mike2ox.ts b/two-sum/mike2ox.ts new file mode 100644 index 000000000..c8c883692 --- /dev/null +++ b/two-sum/mike2ox.ts @@ -0,0 +1,23 @@ +/** + * Source: https://leetcode.com/problems/two-sum/ + * 풀이방법: Map을 이용하여 필요한 나머지 숫자를 저장하면서 확인 + * 시간복잡도: O(n) + * 공간복잡도: O(n) + */ +function twoSum(nums: number[], target: number): number[] { + // nums의 값을 key로, 인덱스를 value로 저장하는 Map + const numMap = new Map(); + + for (let i = 0; i < nums.length; i++) { + const remain = target - nums[i]; // 필요한 나머지 숫자 계산 + + // 필요한 나머지 숫자가 Map에 있는지 체크 + if (numMap.has(remain)) { + return [numMap.get(remain)!, i]; + } + // 현재 숫자와 인덱스 저장 + numMap.set(nums[i], i); + } + + return []; +} From 121d8cee39ef4bd319bc9b25cfaff839751aaffd Mon Sep 17 00:00:00 2001 From: mike2ox Date: Sat, 28 Dec 2024 12:48:43 +0900 Subject: [PATCH 129/183] feat: Upload reverse bits(typescript) --- reverse-bits/mike2ox.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 reverse-bits/mike2ox.ts diff --git a/reverse-bits/mike2ox.ts b/reverse-bits/mike2ox.ts new file mode 100644 index 000000000..ef2524de9 --- /dev/null +++ b/reverse-bits/mike2ox.ts @@ -0,0 +1,16 @@ +/** + * source: https://leetcode.com/problems/reverse-bits/ + * 풀이방법: 비트 연산을 이용하여 뒤집기 + * 시간복잡도: O(1) + * 공간복잡도: O(1) + */ +function reverseBits(n: number): number { + let result = 0; + const bitSize = 32; + // 32비트를 순회하면서 뒤집기 + for (let i = 0; i < bitSize; i++) { + const bit = (n >> i) & 1; // i번째 비트 추출 + result = result | (bit << (bitSize - 1 - i)); // 뒤집은 비트를 result에 저장 + } + return result >>> 0; // 부호비트를 제거하기 위해 0으로 비트 이동 +} From 5a5bbab24bc298846d496fb4935bfb767959e2fd Mon Sep 17 00:00:00 2001 From: mike2ox Date: Sat, 28 Dec 2024 12:52:40 +0900 Subject: [PATCH 130/183] feat: Upload maximum-subarray(typescript) --- maximum-subarray/mike2ox.ts | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 maximum-subarray/mike2ox.ts diff --git a/maximum-subarray/mike2ox.ts b/maximum-subarray/mike2ox.ts new file mode 100644 index 000000000..2c6d74a31 --- /dev/null +++ b/maximum-subarray/mike2ox.ts @@ -0,0 +1,22 @@ +/** + * source: https://leetcode.com/problems/maximum-subarray/ + * 풀이방법: 현재 위치까지의 최대 합을 저장하면서 전체 최대 합을 갱신 + * 시간복잡도: O(n) (n: nums의 길이) + * 공간복잡도: O(1) (상수 공간만 사용) + */ +function maxSubArray(nums: number[]): number { + // 배열이 비어있는 경우 + if (nums.length === 0) return 0; + + let result = nums[0]; // 전체 최대 합(초기값은 첫 번째 요소) + let current = nums[0]; // 현재 위치까지의 최대 합 + + for (let i = 1; i < nums.length; i++) { + // 현재 요소를 더한 값과 현재 요소 중 큰 값을 선택 + current = Math.max(nums[i], current + nums[i]); + // 전체 최대 합 갱신 + result = Math.max(result, current); + } + + return result; +} From 35832fc76fac10b9b0a534adf8ed6005984c5333 Mon Sep 17 00:00:00 2001 From: HiGeuni Date: Sat, 28 Dec 2024 13:40:27 +0900 Subject: [PATCH 131/183] Feat: Week 3 --- product-of-array-except-self/higeuni.js | 24 +++++++++++++++++ reverse-bits/higeuni.js | 36 +++++++++++++++++++++++++ two-sum/higeuni.js | 22 +++++++++++++++ 3 files changed, 82 insertions(+) create mode 100644 product-of-array-except-self/higeuni.js create mode 100644 reverse-bits/higeuni.js create mode 100644 two-sum/higeuni.js diff --git a/product-of-array-except-self/higeuni.js b/product-of-array-except-self/higeuni.js new file mode 100644 index 000000000..3c8a8417b --- /dev/null +++ b/product-of-array-except-self/higeuni.js @@ -0,0 +1,24 @@ +/** + * @param {number[]} nums + * @return {number[]} + * + * Time Complexity: O(n) + * Space Complexity: O(n) + */ +var productExceptSelf = function(nums) { + const answer = [] + const zeros = nums.filter(n => n === 0).length; + if (zeros > 1) return new Array(nums.length).fill(0); + + const productOfNums = nums.reduce((acc, cur) => cur === 0 ? acc : acc * cur, 1); + + nums.forEach(num => { + if (num === 0) { + answer.push(productOfNums); + } else { + answer.push(zeros ? 0 : productOfNums / num); + } + }); + return answer +}; + diff --git a/reverse-bits/higeuni.js b/reverse-bits/higeuni.js new file mode 100644 index 000000000..51cb54c04 --- /dev/null +++ b/reverse-bits/higeuni.js @@ -0,0 +1,36 @@ +/** + * @param {number} n - a positive integer + * @return {number} - a positive integer + * + * Time Complexity: O(n)? n이 32이기 때문에 O(1)? + * Space Complexity: O(1) + */ + +// 일반적인 풀이 +var reverseBits = function(n) { + const binary = n.toString(2); + const reversedBinary = binary.split('').reverse().join('').padEnd(32, '0'); + const answer = parseInt(reversedBinary, 2); + + return answer; + // return parseInt(n.toString(2).split('').reverse().join('').padEnd(32, '0'), 2); +}; + +/** + * + * Time Complexity: O(1) + * Space Complexity: O(1) +*/ + +// 비트 연산을 이용한 풀이 +var reverseBits2 = function(n) { + let result = 0; + for(let i = 0; i < 32; i++) { + // result를 왼쪽으로 시프트하고 n의 마지막 비트를 더함 + result = (result << 1) | (n & 1); + // n을 오른쪽으로 시프트 + n = n >> 1; + } + return result >>> 0; +} + diff --git a/two-sum/higeuni.js b/two-sum/higeuni.js new file mode 100644 index 000000000..466f99ddd --- /dev/null +++ b/two-sum/higeuni.js @@ -0,0 +1,22 @@ +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + * + * Time Complexity: O(n) + * Space Complexity: O(n) + */ +var twoSum = function(nums, target) { + const map = new Map(); + + for (let i = 0; i < nums.length; ++i) { + const diff = target - nums[i]; + + if (map.has(diff)) { + return [map.get(diff), i]; + } + + map.set(nums[i], i); + } +}; + From 225d19e2c7b4f1fb914c394a726fefc333732d5b Mon Sep 17 00:00:00 2001 From: mike2ox Date: Sat, 28 Dec 2024 13:54:19 +0900 Subject: [PATCH 132/183] feat: Upload product-of-array-except-self(typescript) --- product-of-array-except-self/mike2ox.ts | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 product-of-array-except-self/mike2ox.ts diff --git a/product-of-array-except-self/mike2ox.ts b/product-of-array-except-self/mike2ox.ts new file mode 100644 index 000000000..4d01e4738 --- /dev/null +++ b/product-of-array-except-self/mike2ox.ts @@ -0,0 +1,25 @@ +/** + * source: https://leetcode.com/problems/product-of-array-except-self/ + * 풀이방법: 왼쪽부터의 누적 곱과 오른쪽부터의 누적 곱을 이용하여 결과 계산 + * 시간복잡도: O(n) (n: nums의 길이) + * 공간복잡도: O(1) (상수 공간만 사용) + */ +function productExceptSelf(nums: number[]): number[] { + const n = nums.length; + const result = new Array(n); + + // 왼쪽부터의 누적 곱 계산 + result[0] = 1; + for (let i = 1; i < n; i++) { + result[i] = result[i - 1] * nums[i - 1]; + } + + // 오른쪽부터의 누적 곱을 곱하면서 결과 계산 + let right = 1; + for (let i = n - 1; i >= 0; i--) { + result[i] = result[i] * right; + right *= nums[i]; + } + + return result; +} From 97a8b738583afaca16f790d08f2dd4b55c20bf82 Mon Sep 17 00:00:00 2001 From: mike2ox Date: Sat, 28 Dec 2024 13:58:25 +0900 Subject: [PATCH 133/183] feat: Upload combination-sum(typescript) --- combination-sum/mike2ox.ts | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 combination-sum/mike2ox.ts diff --git a/combination-sum/mike2ox.ts b/combination-sum/mike2ox.ts new file mode 100644 index 000000000..1e774c0cc --- /dev/null +++ b/combination-sum/mike2ox.ts @@ -0,0 +1,27 @@ +/** + * source: https://leetcode.com/problems/combination-sum/ + * 풀이방법: 재귀를 이용하여 모든 조합을 탐색 + * + * 시간복잡도: O(n^m) (n: candidates의 길이, m: target을 만들기 위한 최대 반복 횟수) + * 공간복잡도: O(n^m) (n: candidates의 길이, m: target을 만들기 위한 최대 반복 횟수) + * + * Note + * - 당장에 구현하려다보니 재귀를 이용한 방법으로 구현. => 추후 리팩토링 필요 + */ +function combinationSum(candidates: number[], target: number): number[][] { + if (target === 0) return [[]]; + if (target < 0) return []; + + const result: number[][] = []; + + for (let i = 0; i < candidates.length; i++) { + const num = candidates[i]; + const subCombos = combinationSum(candidates.slice(i), target - num); + + for (const combo of subCombos) { + result.push([num, ...combo]); + } + } + + return result; +} From f4361667ab1ccce9b99f00123c8c17e72b0f65a9 Mon Sep 17 00:00:00 2001 From: YeomChaeeun Date: Sat, 28 Dec 2024 14:37:25 +0900 Subject: [PATCH 134/183] feat: product-of-array-except-self solution --- product-of-array-except-self/YeomChaeeun.ts | 47 +++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 product-of-array-except-self/YeomChaeeun.ts diff --git a/product-of-array-except-self/YeomChaeeun.ts b/product-of-array-except-self/YeomChaeeun.ts new file mode 100644 index 000000000..43f5e6ad7 --- /dev/null +++ b/product-of-array-except-self/YeomChaeeun.ts @@ -0,0 +1,47 @@ +/** + * 본인 인덱스에 있는 값을 제외한 모든 수의 곱 + * 알고리즘 복잡도 + * - 시간복잡도: O(n) + * - 공간복잡도: O(1) + * @param nums + */ +function productExceptSelf(nums: number[]): number[] { + let len = nums.length + let output = Array(len).fill(1) + + /* ex) [1, 2, 3, 4] + left >>> + i = 0 -> 1 = 1 + i = 1 -> 1 * 1 = 1 + i = 2 -> 1 * 1 * 2 = 2 + i = 3 -> 1 * 1 * 2 * 3 = 6 + */ + // 왼쪽부터 누적 곱 + let left = 1 + for (let i = 0; i < len; i++) { + output[i] *= left + left *= nums[i] + } + + /* + right >>> + i = 3 -> 1 = 1 + i = 2 -> 1 * 4 = 4 + i = 1 -> 1 * 4 * 3 = 12 + i = 3 -> 1 * 4 * 3 * 2 = 24 + + output >>> + i = 0 -> 1 * 24 = 24 + i = 1 -> 1 * 12 = 12 + i = 2 -> 2 * 4= 8 + i = 3 -> 6 * 1 = 6 + */ + // 오른쪽부터 누적 곱을 output 각 자리에 곱함 + let right = 1 + for (let i = len - 1; i >= 0; i--) { + output[i] *= right + right *= nums[i] + } + + return output +} From 5cdfab5b6e70d3dff8196237ad85fbf42cb213c2 Mon Sep 17 00:00:00 2001 From: YeomChaeeun Date: Sat, 28 Dec 2024 15:11:02 +0900 Subject: [PATCH 135/183] feat: maximum-subarray solution --- maximum-subarray/YeomChaeeun.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 maximum-subarray/YeomChaeeun.ts diff --git a/maximum-subarray/YeomChaeeun.ts b/maximum-subarray/YeomChaeeun.ts new file mode 100644 index 000000000..ab0e24552 --- /dev/null +++ b/maximum-subarray/YeomChaeeun.ts @@ -0,0 +1,20 @@ +/** + * 연속되는 서브 배열로 최대 합을 구하기 + * 알고리즘 복잡도 + * - 시간 복잡도: O(n) + * - 공간 복잡도: O(1) + * @param nums + */ +function maxSubArray(nums: number[]): number { + if(nums.length === 1) return nums[0] + + let currentSum = nums[0] + let maxSum = nums[0] + for(let i = 1; i < nums.length; i++) { + currentSum = Math.max(nums[i], currentSum + nums[i]) + // 최대값 갱신 + maxSum = Math.max(maxSum, currentSum) + } + + return maxSum +} From ba86e4c5c2f8d12e1c18bf5e6b62ec86e267fcb3 Mon Sep 17 00:00:00 2001 From: Jinho Hyeon Date: Sat, 28 Dec 2024 15:46:50 +0900 Subject: [PATCH 136/183] week03 (#768) --- combination-sum/neverlish.go | 45 +++++++++++++++ maximum-subarray/neverlish.go | 51 +++++++++++++++++ product-of-array-except-self/neverlish.go | 69 +++++++++++++++++++++++ reverse-bits/neverlish.go | 22 ++++++++ two-sum/neverlish.go | 49 ++++++++++++++++ 5 files changed, 236 insertions(+) create mode 100644 combination-sum/neverlish.go create mode 100644 maximum-subarray/neverlish.go create mode 100644 product-of-array-except-self/neverlish.go create mode 100644 reverse-bits/neverlish.go create mode 100644 two-sum/neverlish.go diff --git a/combination-sum/neverlish.go b/combination-sum/neverlish.go new file mode 100644 index 000000000..3e74ee415 --- /dev/null +++ b/combination-sum/neverlish.go @@ -0,0 +1,45 @@ +// 시간복잡도: O(n^2) +// 공간복잡도: O(n^2) + +package main + +import "testing" + +func TestCombinationSum(t *testing.T) { + result1 := combinationSum([]int{2, 3, 6, 7}, 7) + + if len(result1) != 2 { + t.Errorf("Expected 2, got %d", len(result1)) + } + + if len(result1[0]) != 3 && len(result1[1]) != 1 { + t.Errorf("Expected [[7], [2, 2, 3]], got %v", result1) + } + + result2 := combinationSum([]int{2, 3, 5}, 8) + + if len(result2) != 3 { + t.Errorf("Expected 3, got %d", len(result2)) + } + + if len(result2[0]) != 2 && len(result2[1]) != 3 && len(result2[2]) != 3 { + t.Errorf("Expected [[2, 2, 2, 2], [2, 3, 3], [3, 5]], got %v", result2) + } +} + +func combinationSum(candidates []int, target int) [][]int { + dp := make([][][]int, target+1) + + dp[0] = [][]int{{}} + + for _, candidate := range candidates { + for i := candidate; i <= target; i++ { + for _, combination := range dp[i-candidate] { + newCombination := append([]int{candidate}, combination...) + dp[i] = append(dp[i], newCombination) + } + } + } + + return dp[target] +} diff --git a/maximum-subarray/neverlish.go b/maximum-subarray/neverlish.go new file mode 100644 index 000000000..5f0b7b876 --- /dev/null +++ b/maximum-subarray/neverlish.go @@ -0,0 +1,51 @@ +// 시간복잡도: O(n) +// 공간복잡도: O(n) + +package main + +import "testing" + +func TestMaxSubArray(t *testing.T) { + result1 := maxSubArray([]int{-2,1,-3,4,-1,2,1,-5,4}) + + if result1 != 6 { + t.Errorf("Expected 6, got %d", result1) + } + + result2 := maxSubArray([]int{1}) + + if result2 != 1 { + t.Errorf("Expected 1, got %d", result2) + } + + result3 := maxSubArray([]int{5,4,-1,7,8}) + + if result3 != 23 { + t.Errorf("Expected 23, got %d", result3) + } +} + +func max(nums ...int) int { + result := nums[0] + + for _, num := range nums[1:] { + if num > result { + result = num + } + } + + return result +} + +func maxSubArray(nums []int) int { + dp := make([]int, len(nums)) + + dp[0] = nums[0] + + for index, num := range nums[1:] { + dp[index+1] = max(0, dp[index]) + num + + } + + return max(dp...) +} diff --git a/product-of-array-except-self/neverlish.go b/product-of-array-except-self/neverlish.go new file mode 100644 index 000000000..4d8f079c3 --- /dev/null +++ b/product-of-array-except-self/neverlish.go @@ -0,0 +1,69 @@ +// 시간복잡도 : O(n) +// 공간복잡도 : O(1) + +package main + +import "testing" + +func TestProductExceptSelf(t *testing.T) { + test1 := productExceptSelf([]int{1, 2, 3, 4}) + if len(test1) != 4 { + t.Errorf("Expected 4, got %d", len(test1)) + } + + if test1[0] != 24 && test1[1] != 12 && test1[2] != 8 && test1[3] != 6 { + t.Errorf("Expected [24, 12, 8, 6], got %v", test1) + } + + test2 := productExceptSelf([]int{0, 0}) + + if len(test2) != 2 { + t.Errorf("Expected 2, got %d", len(test2)) + } + + if test2[0] != 0 && test2[1] != 0 { + t.Errorf("Expected [0, 0], got %v", test2) + } + + test3 := productExceptSelf([]int{-1,1,0,-3,3}) + if len(test3) != 5 { + t.Errorf("Expected 5, got %d", len(test3)) + } + + if test3[0] != 0 && test3[1] != 0 && test3[2] != 9 && test3[3] != 0 && test3[4] != 0 { + t.Errorf("Expected [0, 0, 9, 0, 0], got %v", test3) + } +} + +func productExceptSelf(nums []int) []int { + zeroCount := 0 + product := 1 + + for _, num := range nums { + if num == 0 { + zeroCount++ + } else { + product *= num + } + } + + result := make([]int, len(nums)) + + if zeroCount > 1 { + return result + } + + for i, num := range nums { + if zeroCount == 1 { + if num == 0 { + result[i] = product + } else { + result[i] = 0 + } + } else { + result[i] = product / num + } + } + + return result +} diff --git a/reverse-bits/neverlish.go b/reverse-bits/neverlish.go new file mode 100644 index 000000000..8405bd9be --- /dev/null +++ b/reverse-bits/neverlish.go @@ -0,0 +1,22 @@ +// 시간복잡도: O(1) +// 공간복잡도: O(1) + +package main + +func reverseBits(num uint32) uint32 { + stack := []uint32{} + + for i := 0; i < 32; i++ { + stack = append(stack, num&1) + num >>= 1 + } + + result := uint32(0) + + for i := 0; i < 32; i++ { + result <<= 1 + result |= stack[i] + } + + return result +} diff --git a/two-sum/neverlish.go b/two-sum/neverlish.go new file mode 100644 index 000000000..b8bc6f067 --- /dev/null +++ b/two-sum/neverlish.go @@ -0,0 +1,49 @@ +// 시간복잡도: O(n) +// 공간복잡도: O(n) + +package main + +import "testing" + +func TestTwoSum(t *testing.T) { + result1 := twoSum([]int{2, 7, 11, 15}, 9) + + if len(result1) != 2 { + t.Errorf("Expected 2, got %d", len(result1)) + } + + if result1[0] != 0 && result1[1] != 1 { + t.Errorf("Expected [0, 1], got %v", result1) + } + + result2 := twoSum([]int{3, 2, 4}, 6) + + if len(result2) != 2 { + t.Errorf("Expected 2, got %d", len(result2)) + } + + if result2[0] != 1 && result2[1] != 2 { + t.Errorf("Expected [1, 2], got %v", result2) + } + + result3 := twoSum([]int{3, 3}, 6) + if len(result3) != 2 { + t.Errorf("Expected 2, got %d", len(result3)) + } + + if result3[0] != 0 && result3[1] != 1 { + t.Errorf("Expected [0, 1], got %v", result3) + } +} + +func twoSum(nums []int, target int) []int { + seen := map[int]int{} + for i, num := range nums { + complement := target - num + if _, ok := seen[complement]; ok { + return []int{seen[complement], i} + } + seen[num] = i + } + return nil +} From d6f44bf3c4d4b0a0bf4bc4d85495d4d616bd3e77 Mon Sep 17 00:00:00 2001 From: jeehay Date: Sat, 28 Dec 2024 16:44:02 +0900 Subject: [PATCH 137/183] Add reverse-bits solution --- reverse-bits/Jeehay28.js | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 reverse-bits/Jeehay28.js diff --git a/reverse-bits/Jeehay28.js b/reverse-bits/Jeehay28.js new file mode 100644 index 000000000..e69de29bb From f0bf882eb228c4333495bdb1d54853535ec6979e Mon Sep 17 00:00:00 2001 From: donghyeon95 Date: Sat, 28 Dec 2024 16:46:32 +0900 Subject: [PATCH 138/183] feat: Product of Array Except Self #239 --- product-of-array-except-self/donghyeon95.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 product-of-array-except-self/donghyeon95.java diff --git a/product-of-array-except-self/donghyeon95.java b/product-of-array-except-self/donghyeon95.java new file mode 100644 index 000000000..016c0b0aa --- /dev/null +++ b/product-of-array-except-self/donghyeon95.java @@ -0,0 +1,31 @@ +class Solution { + public int[] productExceptSelf(int[] nums) { + int[] result = new int[nums.length]; + int[] right = new int[nums.length]; + int[] left = new int[nums.length]; + + // -> 이쪽 방향으로 한번 계산 + right[0] = nums[0]; + for (int i=1; i-1; i--) { + left[i] = left[i+1]*nums[i]; + } + + // f(i) = right(i-1) * left(i+1) + result[0] = left[1]; + result[nums.length-1] = right[nums.length-2]; + for (int i=1; i Date: Sat, 28 Dec 2024 17:43:44 +0900 Subject: [PATCH 139/183] Add reverse-bits solution --- reverse-bits/Jeehay28.js | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/reverse-bits/Jeehay28.js b/reverse-bits/Jeehay28.js index e69de29bb..dac5890e0 100644 --- a/reverse-bits/Jeehay28.js +++ b/reverse-bits/Jeehay28.js @@ -0,0 +1,33 @@ +/** + * @param {number} n - a positive integer + * @return {number} - a positive integer + */ + +// Time Complexity: O(1) +// Space Complexity: O(1) + +var reverseBits = function (n) { + + let stack = []; + let num = n; + + for (let i = 0; i < 32; i++) { + + stack.push(num % 2); + num = Math.floor(num / 2); + } + + stack = stack.reverse(); + + + let result = 0; + + for (let i = 0; i < 32; i++) { + + result += stack[i] * Math.pow(2, i); + + } + + return result; + +}; \ No newline at end of file From 40d6d563cb6521baa4cb5ce1f112c8bfb7123668 Mon Sep 17 00:00:00 2001 From: jeehay Date: Sat, 28 Dec 2024 17:45:13 +0900 Subject: [PATCH 140/183] Add reverse-bits solution --- reverse-bits/Jeehay28.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/reverse-bits/Jeehay28.js b/reverse-bits/Jeehay28.js index dac5890e0..4e9330264 100644 --- a/reverse-bits/Jeehay28.js +++ b/reverse-bits/Jeehay28.js @@ -30,4 +30,6 @@ var reverseBits = function (n) { return result; -}; \ No newline at end of file +}; + + From 4fa6523e70cf80ed6de334342ee984458e771d2b Mon Sep 17 00:00:00 2001 From: jeehay Date: Sat, 28 Dec 2024 17:53:06 +0900 Subject: [PATCH 141/183] Add product-of-array-except-self solution --- product-of-array-except-self/Jeehay28.js | 30 ++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 product-of-array-except-self/Jeehay28.js diff --git a/product-of-array-except-self/Jeehay28.js b/product-of-array-except-self/Jeehay28.js new file mode 100644 index 000000000..0672ca6d2 --- /dev/null +++ b/product-of-array-except-self/Jeehay28.js @@ -0,0 +1,30 @@ +/** + * @param {number[]} nums + * @return {number[]} + */ + +// Time Complexity: O(n) +// Space Complexity: O(n) +var productExceptSelf = function (nums) { + + let result = []; + + let left = Array(nums.length).fill(1) + let right = Array(nums.length).fill(1) + + for (let i = 1; i < nums.length; i++) { + + left[i] = left[i - 1] * nums[i - 1]; + right[nums.length - 1 - i] = right[right.length - i] * nums[nums.length - i] + + } + + for (let i = 0; i < nums.length; i++) { + result[i] = left[i] * right[i]; + } + + return result; + + +}; + From 39f7cdfc37bd6ea4892b11ff26d2a6cb2ea1d8f5 Mon Sep 17 00:00:00 2001 From: donghyeon95 Date: Sat, 28 Dec 2024 18:15:04 +0900 Subject: [PATCH 142/183] feat: Combination Sum #254 --- combination-sum/donghyeon95.java | 60 ++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 combination-sum/donghyeon95.java diff --git a/combination-sum/donghyeon95.java b/combination-sum/donghyeon95.java new file mode 100644 index 000000000..007154ab3 --- /dev/null +++ b/combination-sum/donghyeon95.java @@ -0,0 +1,60 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.stream.Collectors; + +class Solution { + private HashMap> dp = new HashMap<>(); + private HashSet set; + + public List> combinationSum(int[] candidates, int target) { + set = new HashSet<>(Arrays.stream(candidates).boxed().toList()); + recurse(target); + // Convert dp entries back to List> for return + return dp.getOrDefault(target, new ArrayList<>()).stream() + .map(str -> Arrays.stream(str.split(" ")) + .map(Integer::valueOf) + .collect(Collectors.toList())) + .collect(Collectors.toList()); + } + + public void recurse(int target) { + if (dp.containsKey(target)) return; + + List combinations = new ArrayList<>(); + for (int i = 1; i < target + 1; i++) { + if (set.contains(i)) { + int remaining = target - i; + recurse(remaining); + if (dp.containsKey(remaining)) { + for (String combination : dp.get(remaining)) { + List newCombination = new ArrayList<>(Arrays.stream(combination.split(" ")) + .map(Integer::valueOf) + .toList()); + newCombination.add(i); + newCombination.sort(Comparator.reverseOrder()); + + String newCombinationStr = newCombination.stream() + .map(String::valueOf) + .collect(Collectors.joining(" ")); + if (!combinations.contains(newCombinationStr)) { + combinations.add(newCombinationStr); + } + } + } + } + } + if (set.contains(target)) { + String singleCombination = String.valueOf(target); + if (!combinations.contains(singleCombination)) { + combinations.add(singleCombination); + } + } + dp.put(target, combinations); + } + +} + From 150b12c2babfedd0c0b34cb59c88b7943778c935 Mon Sep 17 00:00:00 2001 From: donghyeon95 Date: Sat, 28 Dec 2024 18:26:42 +0900 Subject: [PATCH 143/183] feat: Maximum Subarray #275 --- maximum-subarray/donghyeon95.java | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 maximum-subarray/donghyeon95.java diff --git a/maximum-subarray/donghyeon95.java b/maximum-subarray/donghyeon95.java new file mode 100644 index 000000000..533e64227 --- /dev/null +++ b/maximum-subarray/donghyeon95.java @@ -0,0 +1,22 @@ +import java.util.Arrays; + +class Solution { + public int maxSubArray(int[] nums) { + int max = Integer.MIN_VALUE; + int current = 0; + + for (int num: nums) { + System.out.println(num + " " +max); + if (current + num >=0) { + max = Math.max(max, current+num); + current = current+num; + } else { + current = 0; + } + } + + // 전부 음수일 경우 => 가장 큰수 return + return max>=0? max: Arrays.stream(nums).max().getAsInt(); + } +} + From d818f00ed27f9002fd1d1b372af61d2572dd3a7e Mon Sep 17 00:00:00 2001 From: forest000014 Date: Sat, 28 Dec 2024 20:15:12 +0900 Subject: [PATCH 144/183] Combination Sum --- combination-sum/forest000014.java | 41 +++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 combination-sum/forest000014.java diff --git a/combination-sum/forest000014.java b/combination-sum/forest000014.java new file mode 100644 index 000000000..0dffecf82 --- /dev/null +++ b/combination-sum/forest000014.java @@ -0,0 +1,41 @@ +/* +time complexity: O(nlogn) +- nums 배열(=candidates) 정렬: O(nlogn) +- 재귀 호출 부분은 시간 복잡도를 계산하기가 어렵네요.. candidates 배열을 정렬해두어서, target까지 남은 차이가 현재 확인하고 있는 candidate보다 작다면 루프를 빠져나오게 해서 O(n^t)보다는 작을 텐데, 이런 경우에는 어떻게 표현해야 적절한지 잘 모르겠습니다. + +space complexity: O(1) - 정답으로 사용한 이중 List는 제외 + +*/ + +class Solution { + ArrayList nums; + + public List> combinationSum(int[] candidates, int target) { + nums = Arrays.stream(candidates) + .boxed() + .collect(Collectors.toCollection(ArrayList::new)); + + Collections.sort(nums); + + return calc(target, 0); + } + + private List> calc(int target, int curr) { + if (target == 0) { + ArrayList> lists = new ArrayList<>(); + lists.add(new ArrayList<>()); + return lists; + } + + List> ret = new ArrayList<>(); + boolean found = false; + for (int i = curr; i < nums.size() && nums.get(i) <= target; i++) { + List> results = calc(target - nums.get(i), i); + for (List result : results) { + result.add(nums.get(i)); + ret.add(result); + } + } + return ret; + } +} From 0cd8146c232f10a757b5da395a7164575c80d308 Mon Sep 17 00:00:00 2001 From: Paik Date: Sat, 28 Dec 2024 21:32:26 +0900 Subject: [PATCH 145/183] refactor: feat: 238. Product of Array Except Self --- product-of-array-except-self/gwbaik9717.js | 31 ++++++++-------------- 1 file changed, 11 insertions(+), 20 deletions(-) diff --git a/product-of-array-except-self/gwbaik9717.js b/product-of-array-except-self/gwbaik9717.js index e779083ef..bc9a20eea 100644 --- a/product-of-array-except-self/gwbaik9717.js +++ b/product-of-array-except-self/gwbaik9717.js @@ -6,28 +6,19 @@ * @return {number[]} */ var productExceptSelf = function (nums) { - let count0 = 0; + const n = nums.length; + const fromLeft = Array.from({ length: n + 1 }, () => 1); + const fromRight = Array.from({ length: n + 1 }, () => 1); - const totalProduct = nums.reduce((acc, num) => { - if (num === 0) { - count0++; - } + for (let i = 1; i <= n; i++) { + fromLeft[i] = fromLeft[i - 1] * nums[i - 1]; + } - return acc * num; - }, 1); + for (let i = n - 1; i >= 0; i--) { + fromRight[i] = fromRight[i + 1] * nums[i]; + } - return nums.map((num) => { - if (num === 0) { - // 0이 2 개 이상 존재할 때 - if (count0 > 1) { - return 0; - } - - // 0이 1 개 존재할 때 - // 0을 제외한 나머지 product 계산 (이 과정은 단 한번만 존재하기 때문에 시간 복잡도는 여전히 O(n)) - return nums.filter((num) => num !== 0).reduce((a, c) => a * c, 1); - } - - return totalProduct / num; + return nums.map((num, i) => { + return fromLeft[i] * fromRight[i + 1]; }); }; From 54d1bcffb4eeb67b0332686e95048fd721ee4762 Mon Sep 17 00:00:00 2001 From: jeehay Date: Sat, 28 Dec 2024 22:06:04 +0900 Subject: [PATCH 146/183] Add maximum-subarray solution --- maximum-subarray/Jeehay28.js | 46 ++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 maximum-subarray/Jeehay28.js diff --git a/maximum-subarray/Jeehay28.js b/maximum-subarray/Jeehay28.js new file mode 100644 index 000000000..dac016dcc --- /dev/null +++ b/maximum-subarray/Jeehay28.js @@ -0,0 +1,46 @@ +/** + * @param {number[]} nums + * @return {number} + */ + +// Dynamic programming + + +// Optimized Solution: +// Time Complexity: O(n) +// Space Complexity: O(1) + + +var maxSubArray = function (nums) { + + let currentMax = nums[0]; + let globalMax = nums[0] + + for (let i = 1; i < nums.length; i++) { + + currentMax = Math.max(currentMax + nums[i], nums[i]); + globalMax = Math.max(currentMax, globalMax); + + } + + return globalMax; + +}; + + +// Time Complexity: O(n) +// Space Complexity: O(n) + +// var maxSubArray = function (nums) { + +// let dp = [nums[0]]; + +// for (let i = 1; i < nums.length; i++) { + +// dp[i] = Math.max(dp[i - 1] + nums[i], nums[i]) + +// } + +// return Math.max(...dp) + +// }; \ No newline at end of file From 84283abfac54e8583b849646058da16bcfb82f61 Mon Sep 17 00:00:00 2001 From: jeehay Date: Sat, 28 Dec 2024 22:09:32 +0900 Subject: [PATCH 147/183] Add a newline at the end of the code --- maximum-subarray/Jeehay28.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/maximum-subarray/Jeehay28.js b/maximum-subarray/Jeehay28.js index dac016dcc..a2ec53675 100644 --- a/maximum-subarray/Jeehay28.js +++ b/maximum-subarray/Jeehay28.js @@ -43,4 +43,6 @@ var maxSubArray = function (nums) { // return Math.max(...dp) -// }; \ No newline at end of file +// }; + + From c787f3368362b3cbdc60c64fce748aa123df58b9 Mon Sep 17 00:00:00 2001 From: Paik Date: Sat, 28 Dec 2024 22:20:19 +0900 Subject: [PATCH 148/183] feat: 39. Combination Sum --- combination-sum/gwbaik9717.js | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 combination-sum/gwbaik9717.js diff --git a/combination-sum/gwbaik9717.js b/combination-sum/gwbaik9717.js new file mode 100644 index 000000000..e5675acf5 --- /dev/null +++ b/combination-sum/gwbaik9717.js @@ -0,0 +1,32 @@ +/** + * @param {number[]} candidates + * @param {number} target + * @return {number[][]} + */ +var combinationSum = function (candidates, target) { + const answer = []; + const n = candidates.length; + const combi = (i, sum, arr) => { + for (let j = i; j < n; j++) { + const candidate = candidates[j]; + const newSum = sum + candidate; + + if (newSum === target) { + answer.push([...arr, candidate]); + continue; + } + + if (newSum > target) { + continue; + } + + if (newSum < target) { + combi(j, newSum, [...arr, candidate]); + } + } + }; + + combi(0, 0, []); + + return answer; +}; From c03226623188bd1ae0a29ac47eddb2581ac46c8c Mon Sep 17 00:00:00 2001 From: "daeho.kim" Date: Sat, 28 Dec 2024 22:27:15 +0900 Subject: [PATCH 149/183] feat: two-sum --- two-sum/HodaeSsi.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 two-sum/HodaeSsi.py diff --git a/two-sum/HodaeSsi.py b/two-sum/HodaeSsi.py new file mode 100644 index 000000000..0142a77e8 --- /dev/null +++ b/two-sum/HodaeSsi.py @@ -0,0 +1,13 @@ +# 시간복잡도 : O(n) +# 공간복잡도 : O(n) +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + seen = {} # {num: idx, ...} + + for i, num in enumerate(nums): + if target - num in seen: + return [seen[target - num], i] + seen[num] = i + + return [] + From e48ec469530aeb7c68a0613b11901f93ad84525d Mon Sep 17 00:00:00 2001 From: "daeho.kim" Date: Sat, 28 Dec 2024 22:27:15 +0900 Subject: [PATCH 150/183] feat: reverse-bits --- reverse-bits/HodaeSsi.py | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 reverse-bits/HodaeSsi.py diff --git a/reverse-bits/HodaeSsi.py b/reverse-bits/HodaeSsi.py new file mode 100644 index 000000000..6b67b91e2 --- /dev/null +++ b/reverse-bits/HodaeSsi.py @@ -0,0 +1,5 @@ +# 시간복잡도: O(1) (32bit) +class Solution: + def reverseBits(self, n: int) -> int: + return int(bin(n)[2:].zfill(32)[::-1], 2) + From b9e028deca9b491d443a9d9bbd271a6e13675516 Mon Sep 17 00:00:00 2001 From: "daeho.kim" Date: Sat, 28 Dec 2024 22:27:15 +0900 Subject: [PATCH 151/183] feat: product-of-array-except-self --- product-of-array-except-self/HodaeSsi.py | 30 ++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 product-of-array-except-self/HodaeSsi.py diff --git a/product-of-array-except-self/HodaeSsi.py b/product-of-array-except-self/HodaeSsi.py new file mode 100644 index 000000000..c77f6bc7e --- /dev/null +++ b/product-of-array-except-self/HodaeSsi.py @@ -0,0 +1,30 @@ +# 시간복잡도: O(n) +# 공간복잡도: O(n) +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + prefix = [1] * len(nums) + suffix = [1] * len(nums) + product = [1] * len(nums) + + for idx in range(len(nums)): + if idx == 0: + prefix[idx] = nums[idx] + else: + prefix[idx] = prefix[idx - 1] * nums[idx] + + for idx in range(len(nums) - 1, -1, -1): + if idx == len(nums) - 1: + suffix[idx] = nums[idx] + else: + suffix[idx] = suffix[idx + 1] * nums[idx] + + for idx in range(len(nums)): + if idx == 0: + product[idx] = suffix[idx + 1] + elif idx == len(nums) - 1: + product[idx] = prefix[idx - 1] + else: + product[idx] = prefix[idx - 1] * suffix[idx + 1] + + return product + From bd7c41309d24baf28e4027397f64bebead173684 Mon Sep 17 00:00:00 2001 From: "daeho.kim" Date: Sat, 28 Dec 2024 22:27:15 +0900 Subject: [PATCH 152/183] feat: combination-sum --- combination-sum/HodaeSsi.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 combination-sum/HodaeSsi.py diff --git a/combination-sum/HodaeSsi.py b/combination-sum/HodaeSsi.py new file mode 100644 index 000000000..a5cb50ce5 --- /dev/null +++ b/combination-sum/HodaeSsi.py @@ -0,0 +1,16 @@ +# 시간복잡도 : O(n * m) (n: target, m: len(candidates)) +# 공간복잡도 : O(n * m) +class Solution: + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + dp = [[] for _ in range(target + 1)] + dp[0] = [[]] + + for candidate in candidates: + for num in range(candidate, target + 1): + for combination in dp[num - candidate]: + temp = combination.copy() + temp.extend([candidate]) + dp[num].append(temp) + + return dp[target] + From ffbcf9ab1001d4511fdad014834e60d4156c5954 Mon Sep 17 00:00:00 2001 From: "daeho.kim" Date: Sat, 28 Dec 2024 22:27:15 +0900 Subject: [PATCH 153/183] feat: maximum-subarray --- maximum-subarray/HodaeSsi.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 maximum-subarray/HodaeSsi.py diff --git a/maximum-subarray/HodaeSsi.py b/maximum-subarray/HodaeSsi.py new file mode 100644 index 000000000..e0b1dbf0e --- /dev/null +++ b/maximum-subarray/HodaeSsi.py @@ -0,0 +1,13 @@ +# 시간복잡도 : O(N) +# 공간복잡도 : O(1) +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + global_sum = nums[0] + local_sum = nums[0] + + for i in range(1, len(nums)): + local_sum = max(nums[i], local_sum + nums[i]) + global_sum = max(local_sum, global_sum) + + return global_sum + From 778ae3e55e7c09590c1af26966568ad3dea8122d Mon Sep 17 00:00:00 2001 From: Paik Date: Sat, 28 Dec 2024 22:32:46 +0900 Subject: [PATCH 154/183] feat: 53. Maximum Subarray --- maximum-subarray/gwbaik9717.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 maximum-subarray/gwbaik9717.js diff --git a/maximum-subarray/gwbaik9717.js b/maximum-subarray/gwbaik9717.js new file mode 100644 index 000000000..a4aa473a6 --- /dev/null +++ b/maximum-subarray/gwbaik9717.js @@ -0,0 +1,18 @@ +// Time complexity: O(n) +// Space complexity: O(n) + +/** + * @param {number[]} nums + * @return {number} + */ +var maxSubArray = function (nums) { + const n = nums.length; + const dp = Array.from({ length: n + 1 }, () => Number.MIN_SAFE_INTEGER); + dp[0] = 0; + + for (let i = 1; i <= n; i++) { + dp[i] = Math.max(dp[i - 1] + nums[i - 1], nums[i - 1]); + } + + return Math.max(...dp.slice(1)); +}; From 14b4517faf926c27a1ceffcda2a74da3186a6839 Mon Sep 17 00:00:00 2001 From: paragon0107 <66520077+paragon0107@users.noreply.github.com> Date: Sat, 28 Dec 2024 22:35:27 +0900 Subject: [PATCH 155/183] Delete leetcode-study.iml --- leetcode-study.iml | 82 ---------------------------------------------- 1 file changed, 82 deletions(-) delete mode 100644 leetcode-study.iml diff --git a/leetcode-study.iml b/leetcode-study.iml deleted file mode 100644 index 0184c1642..000000000 --- a/leetcode-study.iml +++ /dev/null @@ -1,82 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file From b3cd465058cb51da31627ceb41b49dc0c87b8eb7 Mon Sep 17 00:00:00 2001 From: Paik Date: Sat, 28 Dec 2024 22:46:38 +0900 Subject: [PATCH 156/183] refactor: feat: 53. Maximum Subarray --- maximum-subarray/gwbaik9717.js | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/maximum-subarray/gwbaik9717.js b/maximum-subarray/gwbaik9717.js index a4aa473a6..e54d84a52 100644 --- a/maximum-subarray/gwbaik9717.js +++ b/maximum-subarray/gwbaik9717.js @@ -1,5 +1,5 @@ // Time complexity: O(n) -// Space complexity: O(n) +// Space complexity: O(1) /** * @param {number[]} nums @@ -7,12 +7,19 @@ */ var maxSubArray = function (nums) { const n = nums.length; - const dp = Array.from({ length: n + 1 }, () => Number.MIN_SAFE_INTEGER); - dp[0] = 0; + const dp = [0, 0]; + + let answer = Number.MIN_SAFE_INTEGER; for (let i = 1; i <= n; i++) { - dp[i] = Math.max(dp[i - 1] + nums[i - 1], nums[i - 1]); + if (i % 2 !== 0) { + dp[1] = Math.max(dp[0] + nums[i - 1], nums[i - 1]); + answer = Math.max(answer, dp[1]); + } else { + dp[0] = Math.max(dp[1] + nums[i - 1], nums[i - 1]); + answer = Math.max(answer, dp[0]); + } } - return Math.max(...dp.slice(1)); + return answer; }; From 9973c729c76aadd0ae1da143752553c9bcb7c2a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=8B=E1=85=B5=E1=84=8B=E1=85=A7=E1=86=AB=E1=84=89?= =?UTF-8?q?=E1=85=AE?= Date: Sun, 29 Dec 2024 00:37:41 +0900 Subject: [PATCH 157/183] product of array except self --- .../EcoFriendlyAppleSu.kt | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 product-of-array-except-self/EcoFriendlyAppleSu.kt diff --git a/product-of-array-except-self/EcoFriendlyAppleSu.kt b/product-of-array-except-self/EcoFriendlyAppleSu.kt new file mode 100644 index 000000000..0d02151c2 --- /dev/null +++ b/product-of-array-except-self/EcoFriendlyAppleSu.kt @@ -0,0 +1,43 @@ +package leetcode_study + +/* +* 주어진 배열에서 자신 요소를 제외한 나머지 요소의 곱한 배열을 구하는 문제 +* 문제에세 O(n)의 시간 복잡도를 요구하였으나 방법이 떠오르지 않아 고민 후 정답 참조. +* 기준 요소를 중심으로 왼쪽의 총 곱, 오른쪽의 총 곱을 진행하게 되었을 때, 문제를 O(n)의 시간 복잡도로 해결할 수 있음. +* 시간 복잡도: O(n^2) +* 공간 복잡도: O(n) +* */ +fun productExceptSelf00(nums: IntArray): IntArray { + val result = mutableListOf() + + for (i in nums.indices) { + var temp = 1 + for (j in nums.indices) { + if (i == j) continue + temp *= nums[j] + } + result.add(temp) + } + return result.toIntArray() +} + +/* +* 시간 복잡도: O(n) +* 공간 복잡도: O(n) +* */ +fun productExceptSelf01(nums: IntArray): IntArray { + val result = IntArray(nums.size) + + var leftProduct = 1 + for (i in nums.indices) { + result[i] = leftProduct + leftProduct = leftProduct * nums[i] + } + + var rightProduct = 1 + for (i in nums.indices.reversed()) { + result[i] = result[i] * rightProduct + rightProduct = rightProduct * nums[i] + } + return result +} From 024836adc9e3b10b8859a49842adb50e3a22ecbc Mon Sep 17 00:00:00 2001 From: mintheon Date: Sun, 29 Dec 2024 01:53:46 +0900 Subject: [PATCH 158/183] product of array except self solved --- product-of-array-except-self/mintheon.java | 23 ++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 product-of-array-except-self/mintheon.java diff --git a/product-of-array-except-self/mintheon.java b/product-of-array-except-self/mintheon.java new file mode 100644 index 000000000..4261c1610 --- /dev/null +++ b/product-of-array-except-self/mintheon.java @@ -0,0 +1,23 @@ +class Solution { + /** + 공간복잡도: O(n) + 시간복잡도: O(n) + */ + public int[] productExceptSelf(int[] nums) { + int[] answer = new int[nums.length]; + + answer[0] = 1; + for(int i = 1; i < nums.length; i++) { + answer[i] = answer[i - 1] * nums[i - 1]; + } + + int value = 1; + for(int i = nums.length - 1; i >= 0; i--) { + + answer[i] = answer[i] * value; + value *= nums[i]; + } + + return answer; + } +} From 5a8b85e3a31bde4bbe955bb17e47a0bb61a8b908 Mon Sep 17 00:00:00 2001 From: mintheon Date: Sun, 29 Dec 2024 03:58:40 +0900 Subject: [PATCH 159/183] combination sum solved --- combination-sum/mintheon.java | 38 +++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 combination-sum/mintheon.java diff --git a/combination-sum/mintheon.java b/combination-sum/mintheon.java new file mode 100644 index 000000000..7c1e98966 --- /dev/null +++ b/combination-sum/mintheon.java @@ -0,0 +1,38 @@ +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.List; + +class Solution { + /** + 시간복잡도: O(2^n) + 공간복잡도: O(n) + */ + public List> combinationSum(int[] candidates, int target) { + List> answer = new ArrayList<>(); + Deque nums = new ArrayDeque<>(); + + backtracking(candidates, answer, nums, target, 0, 0); + + return answer; + } + + protected void backtracking(int[] candidates, List> answer, Deque nums, int target, int start, int total) { + if(total > target) { + return; + } + + if (total == target) { + answer.add(new ArrayList<>(nums)); + return; + } + + for(int i = start; i < candidates.length; i++) { + int num = candidates[i]; + nums.push(num); + + backtracking(candidates, answer, nums, target, i, total + num); + nums.pop(); + } + } +} From c1d6281d7b1d3eadb25a9da673bb00bcf9820512 Mon Sep 17 00:00:00 2001 From: jinah92 Date: Sun, 29 Dec 2024 13:31:32 +0900 Subject: [PATCH 160/183] =?UTF-8?q?feat:=20week4=20easy=20=EB=AC=B8?= =?UTF-8?q?=EC=A0=9C=20=ED=92=80=EC=9D=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- merge-two-sorted-lists/jinah92.py | 18 ++++++++++++++++++ missing-number/jinah92.py | 12 ++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 merge-two-sorted-lists/jinah92.py create mode 100644 missing-number/jinah92.py diff --git a/merge-two-sorted-lists/jinah92.py b/merge-two-sorted-lists/jinah92.py new file mode 100644 index 000000000..d2fd2b872 --- /dev/null +++ b/merge-two-sorted-lists/jinah92.py @@ -0,0 +1,18 @@ +# O(m+n) times, O(1) spaces +class Solution: + def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: + dummy = ListNode(None) + node = dummy + + while list1 and list2: + if list1.val < list2.val: + node.next = list1 + list1 = list1.next + else: + node.next = list2 + list2 = list2.next + + node = node.next + + node.next = list1 or list2 + return dummy.next diff --git a/missing-number/jinah92.py b/missing-number/jinah92.py new file mode 100644 index 000000000..7c68dc983 --- /dev/null +++ b/missing-number/jinah92.py @@ -0,0 +1,12 @@ +# O(n) times, O(n) spaces +class Solution: + def missingNumber(self, nums: List[int]) -> int: + nums_keys = dict.fromkeys(nums,0) + last = 0 + + for i in range(len(nums)): + if not i in nums_keys: + return i + last += 1 + + return last From 6489b9be0c607d83e3a788d627bfce8cb4eca8f7 Mon Sep 17 00:00:00 2001 From: jinah92 Date: Sun, 29 Dec 2024 15:36:02 +0900 Subject: [PATCH 161/183] =?UTF-8?q?feat:=20week4=20medium=20=EB=AC=B8?= =?UTF-8?q?=EC=A0=9C=ED=92=80=EC=9D=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- coin-change/jinah92.py | 10 ++++++++++ palindromic-substrings/jinah92.py | 18 ++++++++++++++++++ word-search/jinah92.py | 25 +++++++++++++++++++++++++ 3 files changed, 53 insertions(+) create mode 100644 coin-change/jinah92.py create mode 100644 palindromic-substrings/jinah92.py create mode 100644 word-search/jinah92.py diff --git a/coin-change/jinah92.py b/coin-change/jinah92.py new file mode 100644 index 000000000..b528841ea --- /dev/null +++ b/coin-change/jinah92.py @@ -0,0 +1,10 @@ +# O(C*A) times, O(A) spaces +class Solution: + def coinChange(self, coins: List[int], amount: int) -> int: + dp = [0] + [amount + 1] * amount + + for coin in coins: + for i in range(coin, amount + 1): + dp[i] = min(dp[i], dp[i-coin]+1) + + return dp[amount] if dp[amount] < amount + 1 else -1 diff --git a/palindromic-substrings/jinah92.py b/palindromic-substrings/jinah92.py new file mode 100644 index 000000000..d5a4bf0a1 --- /dev/null +++ b/palindromic-substrings/jinah92.py @@ -0,0 +1,18 @@ +# O((LogN)^N) times, O(1) spaces +class Solution: + def countSubstrings(self, s: str) -> int: + sub_str_len = 1 + result = 0 + + while sub_str_len <= len(s): + start_idx = 0 + while start_idx + sub_str_len <= len(s): + sub_str = s[start_idx:start_idx+sub_str_len] + if sub_str == sub_str[::-1]: + result += 1 + start_idx += 1 + + sub_str_len += 1 + + + return result diff --git a/word-search/jinah92.py b/word-search/jinah92.py new file mode 100644 index 000000000..3f568eb95 --- /dev/null +++ b/word-search/jinah92.py @@ -0,0 +1,25 @@ +# O(M*N*4^W) times, O(M*N+W) spaces +class Solution: + def exist(self, board: List[List[str]], word: str) -> bool: + rows, cols = len(board), len(board[0]) + visited = set() + + directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] + + def dfs(row, col, idx): + if idx == len(word): + return True + if not (0 <= row < rows and 0 <= col < cols): + return False + if board[row][col] != word[idx]: + return False + if (row, col) in visited: + return False + + visited.add((row, col)) + result = any(dfs(row+r, col+c, idx+1) for (r, c) in directions) + visited.remove((row, col)) + + return result + + return any(dfs(r, c, 0) for r in range(rows) for c in range(cols)) From 9ab7f5fb566f793fa6df47d8ae28820e92337c04 Mon Sep 17 00:00:00 2001 From: Minji Go Date: Mon, 30 Dec 2024 16:51:47 +0900 Subject: [PATCH 162/183] refactor: complexity of combination sum --- combination-sum/minji-go.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/combination-sum/minji-go.java b/combination-sum/minji-go.java index ab895923a..fac01b813 100644 --- a/combination-sum/minji-go.java +++ b/combination-sum/minji-go.java @@ -2,10 +2,8 @@ Problem: https://leetcode.com/problems/combination-sum/ Description: return a list of all unique combinations of candidates where the chosen numbers sum to target Concept: Array, Backtracking - Time Complexity: O(Nⁿ), Runtime 2ms - Space Complexity: O(N), Memory 44.88MB - - - Time Complexity, Space Complexity를 어떻게 계산해야할지 어렵네요 :( + Time Complexity: O(Nᵀ), Runtime 2ms + Space Complexity: O(T), Memory 44.88MB */ class Solution { public List> answer = new ArrayList<>(); From 402d2bdcb6532e621e42bb4e214bc12c7dcfd60c Mon Sep 17 00:00:00 2001 From: Minji Go Date: Mon, 30 Dec 2024 16:52:05 +0900 Subject: [PATCH 163/183] feat: merge two sorted lists --- merge-two-sorted-lists/minji-go.java | 36 ++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 merge-two-sorted-lists/minji-go.java diff --git a/merge-two-sorted-lists/minji-go.java b/merge-two-sorted-lists/minji-go.java new file mode 100644 index 000000000..e701574fa --- /dev/null +++ b/merge-two-sorted-lists/minji-go.java @@ -0,0 +1,36 @@ +/* + Problem: https://leetcode.com/problems/merge-two-sorted-lists/ + Description: return the head of the merged linked list of two sorted linked lists + Concept: Linked List, Recursion + Time Complexity: O(N+M), Runtime 0ms + Space Complexity: O(1), Memory 42.74MB +*/ + +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode mergeTwoLists(ListNode list1, ListNode list2) { + + ListNode head = new ListNode(0); + ListNode tail = head; + + while(list1 != null || list2 != null) { + if (list2 == null || (list1 != null && list1.val <= list2.val)) { + tail = tail.next = new ListNode(list1.val); + list1 = list1.next; + } else { + tail = tail.next = new ListNode(list2.val); + list2 = list2.next; + } + } + return head.next; + } +} From 75025a307d786dec1369998a963e1214bdd52832 Mon Sep 17 00:00:00 2001 From: Minji Go Date: Mon, 30 Dec 2024 16:52:21 +0900 Subject: [PATCH 164/183] feat: missing number --- missing-number/minji-go.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 missing-number/minji-go.java diff --git a/missing-number/minji-go.java b/missing-number/minji-go.java new file mode 100644 index 000000000..61cc2894f --- /dev/null +++ b/missing-number/minji-go.java @@ -0,0 +1,19 @@ +/* + Problem: https://leetcode.com/problems/missing-number/ + Description: return the only number in the range that is missing from the array. + Concept: Array, Hash Table, Math, Binary Search, Bit Manipulation, Sorting + Time Complexity: O(N), Runtime 0ms + Space Complexity: O(1), Memory 45.71MB +*/ +class Solution { + public int missingNumber(int[] nums) { + int n = nums.length; + int missing = n; + + for(int i=0; i Date: Mon, 30 Dec 2024 20:54:30 +0900 Subject: [PATCH 165/183] feat: [Week 04-1] solve merge-two-sorted-lists --- merge-two-sorted-lists/Chaedie.py | 36 +++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 merge-two-sorted-lists/Chaedie.py diff --git a/merge-two-sorted-lists/Chaedie.py b/merge-two-sorted-lists/Chaedie.py new file mode 100644 index 000000000..23773cd2d --- /dev/null +++ b/merge-two-sorted-lists/Chaedie.py @@ -0,0 +1,36 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def mergeTwoLists( + self, list1: Optional[ListNode], list2: Optional[ListNode] + ) -> Optional[ListNode]: + """ + Solution: + 1) 리스트1 리스트2가 null 이 아닌 동안 list1, list2를 차례대로 줄세운다. + 2) list1이 남으면 node.next = list1로 남은 리스트를 연결한다. + 3) list2가 남으면 list2 를 연결한다. + + Time: O(n) + Space: O(1) + """ + dummy = ListNode() + node = dummy + + while list1 and list2: + if list1.val < list2.val: + node.next = list1 + list1 = list1.next + else: + node.next = list2 + list2 = list2.next + node = node.next + + if list1: + node.next = list1 + elif list2: + node.next = list2 + + return dummy.next From d6d11feb302bf6f8d99452b951ff245e307eb842 Mon Sep 17 00:00:00 2001 From: minji-go Date: Tue, 31 Dec 2024 00:32:11 +0900 Subject: [PATCH 166/183] feat: word search --- word-search/minji-go.java | 47 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 word-search/minji-go.java diff --git a/word-search/minji-go.java b/word-search/minji-go.java new file mode 100644 index 000000000..51ca4eed7 --- /dev/null +++ b/word-search/minji-go.java @@ -0,0 +1,47 @@ +/* + Problem: https://leetcode.com/problems/word-search/ + Description: return true if word exists in the grid + Concept: Array, String, Backtracking, Matrix + Time Complexity: O(MN4ᵀ), Runtime 147ms + Space Complexity: O(MN), Memory 42.11MB +*/ +class Solution { + public char[][] board; + public String word; + public boolean[][] visited; + public int n, m; + + public boolean exist(char[][] board, String word) { + this.board = board; + this.word = word; + this.m = board.length; + this.n = board[0].length; + this.visited = new boolean[m][n]; + + for(int i=0; im-1||nc>n-1||visited[nr][nc]) continue; + if(board[nr][nc]!=word.charAt(i)) continue; + if(wordExists(nr, nc, i+1)) return true; + } + visited[cr][cc] = false; + + return false; + } +} From f625aacc3445b24ac5a7d00effc961f73e73de31 Mon Sep 17 00:00:00 2001 From: minji-go Date: Tue, 31 Dec 2024 01:29:58 +0900 Subject: [PATCH 167/183] feat: palindromic substrings --- palindromic-substrings/minji-go.java | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 palindromic-substrings/minji-go.java diff --git a/palindromic-substrings/minji-go.java b/palindromic-substrings/minji-go.java new file mode 100644 index 000000000..cecce3457 --- /dev/null +++ b/palindromic-substrings/minji-go.java @@ -0,0 +1,27 @@ +/* + Problem: https://leetcode.com/problems/palindromic-substrings/ + Description: return the number of palindromic substrings in it. + Concept: Two Pointers, String, Dynamic Programming + Time Complexity: O(N²), Runtime 6ms + Space Complexity: O(1), Memory 41.62MB +*/ +class Solution { + public int countSubstrings(String s) { + int totalCount = 0; + for(int i=0; i=0 && right Date: Tue, 31 Dec 2024 08:43:37 +0900 Subject: [PATCH 168/183] feat: [Week 04-2] solve missing-number --- missing-number/Chaedie.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 missing-number/Chaedie.py diff --git a/missing-number/Chaedie.py b/missing-number/Chaedie.py new file mode 100644 index 000000000..35f77942b --- /dev/null +++ b/missing-number/Chaedie.py @@ -0,0 +1,17 @@ +""" +Solution: + 1) 배열 정렬 + 2) 0부터 for 문을 돌리는데 index 와 값이 다르면 return index + 3) 끝까지 일치한다면 return 배열의 크기 +Time: O(nlogn) = O(nlogn) + O(n) +Space: O(1) +""" + + +class Solution: + def missingNumber(self, nums: List[int]) -> int: + nums.sort() + for i in range(len(nums)): + if i != nums[i]: + return i + return len(nums) From 5f929c8c5156e21e1c410e81890c646cb447da75 Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Tue, 31 Dec 2024 09:24:18 +0900 Subject: [PATCH 169/183] feat: [Week 04-3] solve word-search --- word-search/Chaedie.py | 126 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 word-search/Chaedie.py diff --git a/word-search/Chaedie.py b/word-search/Chaedie.py new file mode 100644 index 000000000..d1944860c --- /dev/null +++ b/word-search/Chaedie.py @@ -0,0 +1,126 @@ +""" +Solution: + 1) board의 상하좌우를 탐색하되 아래 조건을 base case로 걸러준다. + 1.1) index 가 word의 길이이면 결과값 판단 + 1.2) out of bounds 판단 + 1.3) index를 통해 현재 글자와 board의 글자의 일치 판단 + 1.4) 방문 여부 판단 + 2) board를 돌면서 backtrack 이 True 인 케이스가 있으면 return True + +m = row_len +n = col_len +L = 단어 길이 +Time: O(m n 4^L) +Space: O(mn + L^2) = visit set O(mn) + 호출 스택 및 cur_word O(L^2) +""" + + +class Solution: + def exist(self, board: List[List[str]], word: str) -> bool: + ROWS, COLS = len(board), len(board[0]) + visit = set() + + def backtrack(r, c, index, cur_word): + if index == len(word): + return word == cur_word + if r < 0 or c < 0 or r == ROWS or c == COLS: + return False + if word[index] != board[r][c]: + return False + if (r, c) in visit: + return False + + visit.add((r, c)) + condition = ( + backtrack(r + 1, c, index + 1, cur_word + board[r][c]) + or backtrack(r - 1, c, index + 1, cur_word + board[r][c]) + or backtrack(r, c + 1, index + 1, cur_word + board[r][c]) + or backtrack(r, c - 1, index + 1, cur_word + board[r][c]) + ) + visit.remove((r, c)) + return condition + + for i in range(ROWS): + for j in range(COLS): + if backtrack(i, j, 0, ""): + return True + return False + + +""" +Solution: + 공간 복잡도 낭비를 줄이기 위해 cur_word 제거 +Time: O(m n 4^L) +Space: O(mn + L) +""" + + +class Solution: + def exist(self, board: List[List[str]], word: str) -> bool: + ROWS, COLS = len(board), len(board[0]) + visit = set() + + def backtrack(r, c, index): + if index == len(word): + return True + if r < 0 or c < 0 or r == ROWS or c == COLS: + return False + if word[index] != board[r][c]: + return False + if (r, c) in visit: + return False + + visit.add((r, c)) + condition = ( + backtrack(r + 1, c, index + 1) + or backtrack(r - 1, c, index + 1) + or backtrack(r, c + 1, index + 1) + or backtrack(r, c - 1, index + 1) + ) + visit.remove((r, c)) + return condition + + for i in range(ROWS): + for j in range(COLS): + if backtrack(i, j, 0): + return True + return False + + +""" +Solution: + 공간 복잡도를 줄이기 위해 visit set 제거 + -> board[r][c]에 빈문자열을 잠깐 추가하는것으로 대체 +Time: O(m n 4^L) +Space: O(L) +""" + + +class Solution: + def exist(self, board: List[List[str]], word: str) -> bool: + ROWS, COLS = len(board), len(board[0]) + + def backtrack(r, c, index): + if index == len(word): + return True + if r < 0 or c < 0 or r == ROWS or c == COLS: + return False + if word[index] != board[r][c]: + return False + + temp = board[r][c] + board[r][c] = "" + condition = ( + backtrack(r + 1, c, index + 1) + or backtrack(r - 1, c, index + 1) + or backtrack(r, c + 1, index + 1) + or backtrack(r, c - 1, index + 1) + ) + board[r][c] = temp + return condition + + for i in range(ROWS): + for j in range(COLS): + if backtrack(i, j, 0): + return True + return False From a353a021e27316a2533a3d99655d2fd799cd1cb9 Mon Sep 17 00:00:00 2001 From: Lyla Date: Tue, 31 Dec 2024 14:55:00 -0500 Subject: [PATCH 170/183] solve 3 --- merge-two-sorted-lists/pmjuu.py | 33 ++++++++++ missing-number/pmjuu.py | 13 ++++ word-search/pmjuu.py | 106 ++++++++++++++++++++++++++++++++ 3 files changed, 152 insertions(+) create mode 100644 merge-two-sorted-lists/pmjuu.py create mode 100644 missing-number/pmjuu.py create mode 100644 word-search/pmjuu.py diff --git a/merge-two-sorted-lists/pmjuu.py b/merge-two-sorted-lists/pmjuu.py new file mode 100644 index 000000000..2d9904c77 --- /dev/null +++ b/merge-two-sorted-lists/pmjuu.py @@ -0,0 +1,33 @@ +from typing import Optional + + +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + +class Solution: + def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: + head = ListNode() + current = head + + while list1 and list2: + if list1.val <= list2.val: + current.next = list1 + list1 = list1.next + else: + current.next = list2 + list2 = list2.next + + current = current.next + + current.next = list1 or list2 + + return head.next + +# 시간 복잡도: +# - 두 리스트의 모든 노드를 순회하며 병합하므로 O(n + m) => O(n) 으로 표현 +# 여기서 n은 list1의 길이, m은 list2의 길이. +# +# 공간 복잡도: +# - 기존 노드를 재사용하므로 O(1) diff --git a/missing-number/pmjuu.py b/missing-number/pmjuu.py new file mode 100644 index 000000000..5332417e2 --- /dev/null +++ b/missing-number/pmjuu.py @@ -0,0 +1,13 @@ +from typing import List + + +class Solution: + def missingNumber(self, nums: List[int]) -> int: + n = len(nums) + # 0부터 n까지의 숫자의 합을 수학적 합 공식을 사용해 계산 + total_sum = n * (n + 1) // 2 + + return total_sum - sum(nums) + +# 시간 복잡도 O(n) +# 공간 복잡도 O(1) diff --git a/word-search/pmjuu.py b/word-search/pmjuu.py new file mode 100644 index 000000000..a119c032a --- /dev/null +++ b/word-search/pmjuu.py @@ -0,0 +1,106 @@ +from typing import List + + +class Solution: + def exist(self, board: List[List[str]], word: str) -> bool: + n, m, word_length = len(board), len(board[0]), len(word) + + def search(row, col, word_idx, visited): + # 경계 체크 + if not (0 <= row < n and 0 <= col < m): + return False + # 이미 방문했거나, 문자가 일치하지 않는 경우 + if (row, col) in visited or board[row][col] != word[word_idx]: + return False + + # 모든 문자를 찾은 경우 + if word_idx == word_length - 1: + return True + + # 현재 셀을 방문한 것으로 표시 + visited.add((row, col)) + + # 인접한 셀 확인 + found = ( + search(row - 1, col, word_idx + 1, visited) or + search(row + 1, col, word_idx + 1, visited) or + search(row, col - 1, word_idx + 1, visited) or + search(row, col + 1, word_idx + 1, visited) + ) + # 현재 셀 방문 해제 (백트래킹) + visited.remove((row, col)) + + return found + + # 모든 셀에서 탐색 시작 + for row in range(n): + for col in range(m): + if board[row][col] == word[0]: + if search(row, col, 0, set()): + return True + + return False + +# 풀이 1: 방문 기록을 Set으로 관리하는 방식 +# 시간 복잡도: +# - 각 셀에서 DFS를 시작하며, 각 DFS는 최대 네 방향으로 이동하며 word의 길이만큼 재귀 호출을 진행함. +# - 최악의 경우 O(n * 4^k), 여기서 n은 전체 셀의 개수, k는 word의 길이. +# 공간 복잡도: +# - visited Set 사용: O(k), 여기서 k는 word의 길이. +# - 재귀 호출 스택: O(k), word의 길이만큼 재귀 호출이 쌓임. +# => 총 공간 복잡도: O(k) + + +class Solution: + def exist(self, board: list[list[str]], word: str) -> bool: + n, m = len(board), len(board[0]) + word_length = len(word) + + # 조기 종료: board에 word를 구성할 충분한 문자가 있는지 확인 + from collections import Counter + board_counter = Counter(char for row in board for char in row) + word_counter = Counter(word) + if any(word_counter[char] > board_counter[char] for char in word_counter): + return False + + def search(row, col, idx): + # 기본 조건: 모든 문자가 일치한 경우 + if idx == word_length: + return True + + # 경계 조건 및 문자 일치 여부 확인 + if row < 0 or row >= n or col < 0 or col >= m or board[row][col] != word[idx]: + return False + + # 현재 셀을 방문한 것으로 임시 표시 + temp = board[row][col] + board[row][col] = "#" + + # 모든 방향 탐색 + found = ( + search(row - 1, col, idx + 1) or + search(row + 1, col, idx + 1) or + search(row, col - 1, idx + 1) or + search(row, col + 1, idx + 1) + ) + + # 탐색 후 셀 복원 + board[row][col] = temp + return found + + # 첫 번째 문자와 일치하는 모든 셀에서 DFS 시작 + for i in range(n): + for j in range(m): + if board[i][j] == word[0] and search(i, j, 0): + return True + + return False + +# 풀이 2: Board를 직접 수정해 방문 기록 관리 +# 시간 복잡도: +# - 각 셀에서 DFS를 시작하며, 최대 네 방향으로 이동하며 word의 길이만큼 재귀 호출을 진행함. +# - 최악의 경우 O(n * 4^k), 여기서 n은 전체 셀의 개수, k는 word의 길이. +# 공간 복잡도: +# - 추가 공간 사용 없이 Board를 직접 수정: O(1). +# - 재귀 호출 스택: O(k), word의 길이만큼 재귀 호출이 쌓임. +# => 총 공간 복잡도: O(k) From c981bfbfa14e00cb56447df3ee6380de41e70f33 Mon Sep 17 00:00:00 2001 From: jinah92 Date: Wed, 1 Jan 2025 10:29:34 +0900 Subject: [PATCH 171/183] =?UTF-8?q?feat:=20missing-number=20=EC=95=8C?= =?UTF-8?q?=EA=B3=A0=EB=A6=AC=EC=A6=98=20=EB=A6=AC=ED=8C=A9=ED=86=A0?= =?UTF-8?q?=EB=A7=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - set 자료구조를 활용 - for문을 모두 순회한경우 리스트의 길이를 리턴 --- missing-number/jinah92.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/missing-number/jinah92.py b/missing-number/jinah92.py index 7c68dc983..357bb8070 100644 --- a/missing-number/jinah92.py +++ b/missing-number/jinah92.py @@ -1,12 +1,10 @@ # O(n) times, O(n) spaces class Solution: def missingNumber(self, nums: List[int]) -> int: - nums_keys = dict.fromkeys(nums,0) - last = 0 + nums_keys = set(nums) for i in range(len(nums)): if not i in nums_keys: return i - last += 1 - return last + return len(nums) From 35cfa418ad7b8409b3d7725212a0cbd3c370134d Mon Sep 17 00:00:00 2001 From: jinah92 Date: Wed, 1 Jan 2025 10:33:17 +0900 Subject: [PATCH 172/183] =?UTF-8?q?chore:=20=EC=8B=9C=EA=B0=84=EB=B3=B5?= =?UTF-8?q?=EC=9E=A1=EB=8F=84=20=EC=88=98=EC=A0=95=20=EB=B0=8F=20=EC=84=A4?= =?UTF-8?q?=EB=AA=85=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- palindromic-substrings/jinah92.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/palindromic-substrings/jinah92.py b/palindromic-substrings/jinah92.py index d5a4bf0a1..cdd4da971 100644 --- a/palindromic-substrings/jinah92.py +++ b/palindromic-substrings/jinah92.py @@ -1,4 +1,7 @@ -# O((LogN)^N) times, O(1) spaces +# O(N^3) times, O(1) spaces +# 내부 while문의 관계가 외부 while문의 sub_str_len에 따라 반복횟수가 줄어드므로, 1+2+...N = N(N-1)/2 = O(N2) 시간 소요 +# 추라고 내부 while에서 sub_str_len에 따라 s가 인덱싱되므로 최대 O(N) 시간이 소요 +# 최종적으로 O(N^2 * N) = O(N^3)이 소요됨 class Solution: def countSubstrings(self, s: str) -> int: sub_str_len = 1 From 6bbe08108833f3c96039a0791171bbcc75f6e499 Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Wed, 1 Jan 2025 13:40:41 +0900 Subject: [PATCH 173/183] feat: [Week 04-4] solve palindromic-substrings --- palindromic-substrings/Chaedie.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 palindromic-substrings/Chaedie.py diff --git a/palindromic-substrings/Chaedie.py b/palindromic-substrings/Chaedie.py new file mode 100644 index 000000000..8e7958e83 --- /dev/null +++ b/palindromic-substrings/Chaedie.py @@ -0,0 +1,30 @@ +""" +Solution: + 1) 자신을 기준으로 l,r 포인터로 늘려주면서 같은 문자이면 palindrome + 이를 홀수, 짝수 글자에 대해 2번 진행해주면된다. +Time: O(n^2) = O(n) * O(n/2 * 2) +Space: O(1) + +""" + + +class Solution: + def countSubstrings(self, s: str) -> int: + result = 0 + for i in range(len(s)): + l, r = i, i + while l >= 0 and r < len(s): + if s[l] != s[r]: + break + l -= 1 + r += 1 + result += 1 + + l, r = i, i + 1 + while l >= 0 and r < len(s): + if s[l] != s[r]: + break + l -= 1 + r += 1 + result += 1 + return result From fa4a499a1cd875dbec397dfc0518d25bec744640 Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Wed, 1 Jan 2025 15:41:20 +0900 Subject: [PATCH 174/183] feat: [Week 04-5] solve coin-change --- coin-change/Chaedie.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 coin-change/Chaedie.py diff --git a/coin-change/Chaedie.py b/coin-change/Chaedie.py new file mode 100644 index 000000000..d63671957 --- /dev/null +++ b/coin-change/Chaedie.py @@ -0,0 +1,28 @@ +""" +직접 풀지 못해 알고달레 풀이를 참고했습니다. https://www.algodale.com/problems/coin-change/ + +Solution: + 1) BFS를 통해 모든 동전을 한번씩 넣어보며 amount와 같아지면 return + +(c: coins의 종류 갯수, a: amount) +Time: O(ca) +Space: O(a) +""" + + +class Solution: + def coinChange(self, coins: List[int], amount: int) -> int: + q = deque([(0, 0)]) # (동전 갯수, 누적 금액) + visited = set() + + while q: + count, total = q.popleft() + if total == amount: + return count + if total in visited: + continue + visited.add(total) + for coin in coins: + if total + coin <= amount: + q.append((count + 1, total + coin)) + return -1 From fdf1daead93944aaa7e289938fe3dc88a4f26f9b Mon Sep 17 00:00:00 2001 From: Lyla Date: Wed, 1 Jan 2025 12:02:30 -0500 Subject: [PATCH 175/183] solve 1 --- palindromic-substrings/pmjuu.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 palindromic-substrings/pmjuu.py diff --git a/palindromic-substrings/pmjuu.py b/palindromic-substrings/pmjuu.py new file mode 100644 index 000000000..d3b343552 --- /dev/null +++ b/palindromic-substrings/pmjuu.py @@ -0,0 +1,30 @@ +class Solution: + def countSubstrings(self, s: str) -> int: + n = len(s) + dp = [[False] * n for _ in range(n)] # dp[i][j]는 s[i:j+1]이 팰린드롬인지 나타냄 + count = 0 + + for length in range(1, n + 1): # 부분 문자열 길이 + for i in range(n - length + 1): # 시작 인덱스 + j = i + length - 1 # 끝 인덱스 + + if length == 1: # 길이 1: 항상 팰린드롬 + dp[i][j] = True + elif length == 2: # 길이 2: 두 문자가 같으면 팰린드롬 + dp[i][j] = (s[i] == s[j]) + else: # 그 외의 경우: 양 끝이 같고 내부가 팰린드롬이면 참 + dp[i][j] = (s[i] == s[j] and dp[i + 1][j - 1]) + + if dp[i][j]: + count += 1 + + return count + + +# 시간 복잡도: +# - 이중 반복문으로 모든 부분 문자열을 확인하므로 O(n^2) +# - 각 확인은 O(1)이므로 최종적으로 O(n^2) + +# 공간 복잡도: +# - DP 테이블(dp)은 O(n^2)의 공간을 사용 +# - 추가 변수는 O(1)이므로 전체 공간 복잡도는 O(n^2) From 10d3c49b6aad534e885eb593e02974d710a9b777 Mon Sep 17 00:00:00 2001 From: Lyla Date: Wed, 1 Jan 2025 12:29:33 -0500 Subject: [PATCH 176/183] add second solution --- palindromic-substrings/pmjuu.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/palindromic-substrings/pmjuu.py b/palindromic-substrings/pmjuu.py index d3b343552..41c4ddf8c 100644 --- a/palindromic-substrings/pmjuu.py +++ b/palindromic-substrings/pmjuu.py @@ -1,3 +1,4 @@ +# Dynamic programming class Solution: def countSubstrings(self, s: str) -> int: n = len(s) @@ -28,3 +29,32 @@ def countSubstrings(self, s: str) -> int: # 공간 복잡도: # - DP 테이블(dp)은 O(n^2)의 공간을 사용 # - 추가 변수는 O(1)이므로 전체 공간 복잡도는 O(n^2) + + +# 투 포인터 방식 +class Solution: + def countSubstrings(self, s: str) -> int: + def expand_around_center(left: int, right: int) -> int: + count = 0 + # 좌우로 확장하며 팰린드롬인지 확인 + while left >= 0 and right < len(s) and s[left] == s[right]: + count += 1 + left -= 1 + right += 1 + return count + + total_count = 0 + for i in range(len(s)): + # 홀수 길이 팰린드롬 (중심이 문자 하나) + total_count += expand_around_center(i, i) + # 짝수 길이 팰린드롬 (중심이 문자 두 개) + total_count += expand_around_center(i, i + 1) + + return total_count + +# 시간 복잡도: +# - 각 문자에서 중심을 기준으로 확장하므로 최대 O(n) 확장 +# - 모든 문자에 대해 확장을 시도하므로 O(n^2) + +# 공간 복잡도: +# - 추가 공간 사용 없이 O(1) From ff0482ef6054f0719df789edac2e760b63d9521c Mon Sep 17 00:00:00 2001 From: Lyla Date: Thu, 2 Jan 2025 12:12:24 -0500 Subject: [PATCH 177/183] solve --- coin-change/pmjuu.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 coin-change/pmjuu.py diff --git a/coin-change/pmjuu.py b/coin-change/pmjuu.py new file mode 100644 index 000000000..e9cc8c483 --- /dev/null +++ b/coin-change/pmjuu.py @@ -0,0 +1,25 @@ +from typing import List + + +class Solution: + def coinChange(self, coins: List[int], amount: int) -> int: + # dp[i]: i 금액을 만들기 위해 필요한 최소 동전 개수 + dp = [float('inf')] * (amount + 1) + dp[0] = 0 + + for i in range(1, amount + 1): + for coin in coins: + if coin <= i: + dp[i] = min(dp[i], dp[i - coin] + 1) + + return dp[amount] if dp[amount] != float('inf') else -1 + + +# 시간 복잡도: +# - 외부 반복문은 금액(amount)의 범위에 비례하고 -> O(n) (n은 amount) +# - 내부 반복문은 동전의 개수에 비례하므로 -> O(m) (m은 coins의 길이) +# - 총 시간 복잡도: O(n * m) + +# 공간 복잡도: +# - dp 배열은 금액(amount)의 크기만큼의 공간을 사용하므로 O(n) +# - 추가 공간 사용은 없으므로 총 공간 복잡도: O(n) From 137592b248de9cf1154a03c4a6b8030d55e3aff8 Mon Sep 17 00:00:00 2001 From: jinah92 Date: Fri, 3 Jan 2025 11:08:50 +0900 Subject: [PATCH 178/183] =?UTF-8?q?feat:=20word-search=20=EC=95=8C?= =?UTF-8?q?=EA=B3=A0=EB=A6=AC=EC=A6=98=20=EB=A6=AC=ED=8C=A9=ED=86=A0?= =?UTF-8?q?=EB=A7=81=20-=20=EA=B3=B5=EA=B0=84=EB=B3=B5=EC=9E=A1=EB=8F=84?= =?UTF-8?q?=20=EA=B0=9C=EC=84=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- word-search/jinah92.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/word-search/jinah92.py b/word-search/jinah92.py index 3f568eb95..df3015a93 100644 --- a/word-search/jinah92.py +++ b/word-search/jinah92.py @@ -1,9 +1,8 @@ -# O(M*N*4^W) times, O(M*N+W) spaces +# O(M*N*4^W) times, O(W) spaces class Solution: def exist(self, board: List[List[str]], word: str) -> bool: rows, cols = len(board), len(board[0]) - visited = set() - + directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] def dfs(row, col, idx): @@ -13,13 +12,13 @@ def dfs(row, col, idx): return False if board[row][col] != word[idx]: return False - if (row, col) in visited: - return False - visited.add((row, col)) + temp_val = board[row][col] + board[row][col] = "" + result = any(dfs(row+r, col+c, idx+1) for (r, c) in directions) - visited.remove((row, col)) + board[row][col] = temp_val return result return any(dfs(r, c, 0) for r in range(rows) for c in range(cols)) From e1d03cda2fca3863102f38caf5fbf3945d7f3def Mon Sep 17 00:00:00 2001 From: jinah92 Date: Fri, 3 Jan 2025 11:28:24 +0900 Subject: [PATCH 179/183] =?UTF-8?q?feat:=20Palindromic=20Substrings=20?= =?UTF-8?q?=EC=95=8C=EA=B3=A0=EB=A6=AC=EC=A6=98=20=EA=B0=9C=EC=84=A0=20-?= =?UTF-8?q?=20DP=20=ED=92=80=EC=9D=B4=EB=B2=95=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- palindromic-substrings/jinah92.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/palindromic-substrings/jinah92.py b/palindromic-substrings/jinah92.py index cdd4da971..05e36bad3 100644 --- a/palindromic-substrings/jinah92.py +++ b/palindromic-substrings/jinah92.py @@ -19,3 +19,21 @@ def countSubstrings(self, s: str) -> int: return result + +# DP 풀이 +# O(N^2) times, O(N^2) spaces +# start, end 지점을 순회하면서 이전 계산값을 재사용하여 회문을 파악 +class Solution2: + def countSubstrings(self, s: str) -> int: + dp = {} + + for end in range(len(s)): + for start in range(end, -1, -1): + if start == end: + dp[(start, end)] = True + elif start + 1 == end: + dp[(start, end)] = s[start] == s[end] + else: + dp[(start, end)] = s[start] == s[end] and dp[(start+1, end-1)] + + return list(dp.values()).count(True) From 69b7a792ed14ec45d2f413e1e2695bbd0b6f4544 Mon Sep 17 00:00:00 2001 From: Minji Go Date: Fri, 3 Jan 2025 13:47:33 +0900 Subject: [PATCH 180/183] feat: coin change --- coin-change/minji-go.java | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 coin-change/minji-go.java diff --git a/coin-change/minji-go.java b/coin-change/minji-go.java new file mode 100644 index 000000000..fcc99e4c2 --- /dev/null +++ b/coin-change/minji-go.java @@ -0,0 +1,23 @@ +/* + Problem: https://leetcode.com/problems/coin-change/ + Description: return the fewest number of coins that you need to make up that amount + Concept: Array, Dynamic Programming, Breadth-First Search + Time Complexity: O(N²), Runtime 15ms - N is the amount + Space Complexity: O(N), Memory 44.28MB +*/ +class Solution { + public int coinChange(int[] coins, int amount) { + int[] dp = new int[amount+1]; + Arrays.fill(dp, amount+1); + dp[0]=0; + + for(int i=1; i<=amount; i++){ + for(int coin : coins){ + if(i >= coin) { + dp[i] = Math.min(dp[i], dp[i-coin] +1); + } + } + } + return dp[amount]>amount? -1: dp[amount]; + } +} From ab5674bd09d0748fe131a164c0ec3591f1afe915 Mon Sep 17 00:00:00 2001 From: Minji Go Date: Fri, 3 Jan 2025 17:29:29 +0900 Subject: [PATCH 181/183] refactor: complexity of merge two sorted lists --- merge-two-sorted-lists/minji-go.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/merge-two-sorted-lists/minji-go.java b/merge-two-sorted-lists/minji-go.java index e701574fa..d70eac76f 100644 --- a/merge-two-sorted-lists/minji-go.java +++ b/merge-two-sorted-lists/minji-go.java @@ -3,7 +3,7 @@ Description: return the head of the merged linked list of two sorted linked lists Concept: Linked List, Recursion Time Complexity: O(N+M), Runtime 0ms - Space Complexity: O(1), Memory 42.74MB + Space Complexity: O(N+M), Memory 42.74MB */ /** From d55d0f775bfd62289b8e1b6330b3c7d37b6c8619 Mon Sep 17 00:00:00 2001 From: Minji Go Date: Fri, 3 Jan 2025 17:29:35 +0900 Subject: [PATCH 182/183] refactor: complexity of coin change --- coin-change/minji-go.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/coin-change/minji-go.java b/coin-change/minji-go.java index fcc99e4c2..527a23d8e 100644 --- a/coin-change/minji-go.java +++ b/coin-change/minji-go.java @@ -2,8 +2,8 @@ Problem: https://leetcode.com/problems/coin-change/ Description: return the fewest number of coins that you need to make up that amount Concept: Array, Dynamic Programming, Breadth-First Search - Time Complexity: O(N²), Runtime 15ms - N is the amount - Space Complexity: O(N), Memory 44.28MB + Time Complexity: O(NM), Runtime 15ms - M is the amount + Space Complexity: O(M), Memory 44.28MB */ class Solution { public int coinChange(int[] coins, int amount) { From 333c656839315dc2ec20c869135ba865b616b5ef Mon Sep 17 00:00:00 2001 From: sungjinwi <0202wsj@gmail.com> Date: Fri, 3 Jan 2025 21:22:04 +0900 Subject: [PATCH 183/183] word-search solution --- word-search/sungjinwi.py | 67 ++++++++++++++++++++++++---------------- 1 file changed, 40 insertions(+), 27 deletions(-) diff --git a/word-search/sungjinwi.py b/word-search/sungjinwi.py index b8952f436..b6b8a86ee 100644 --- a/word-search/sungjinwi.py +++ b/word-search/sungjinwi.py @@ -1,34 +1,47 @@ +""" + 풀이 : + 상하좌우 이동한 좌표가 board범위 벗어나면 False + board[m][n]이 word[idx]와 불일치하면 False + 이미 방문했을경우 False + 단어가 완성되면 True + 상하좌우 한칸 이동한칸에 대해 재귀적 호출 + 상하좌우 중 True 있으면 True 없으면 False + + TC : O(M * N * 4 ^ W) + board의 크기에 비례 -> M * N + 단어의 길이 만큼 상하좌우 재귀 호출 -> 4 ^ W + + SC : O(M * N * W) + set의 메모리는 board 크기에 비례 -> M * N + 함수 호출 스택은 단어 길이에 비례 -> W +""" + class Solution: def exist(self, board: List[List[str]], word: str) -> bool: - visit = {} + visit = set() + + def dfs(m: int, n: int, idx: int) -> bool: + if not (0 <= m < row and 0 <= n < col): + return False + if not board[m][n] == word[idx]: + return False + if (m, n) in visit: + return False + if idx == len(word) - 1: + return True + + visit.add((m, n)) + if any (dfs(m + r, n + c, idx + 1) \ + for (r, c) in [(1, 0), (-1, 0), (0, 1), (0, -1)]): + return True + visit.remove((m, n)) + return False + row = len(board) col = len(board[0]) - - def dfs(m : int, n : int, seq : str) : - if visit[m, n] : - return - if not word.startswith(seq + board[m][n]) : - return - visit[(m, n)] = 1 - seq += board[m][n] - if seq == word : - return - if m > 0 : - if (dfs()) : - return True - if down : - dfs() - if left : - dfs() - if right : - dfs() - visit(m, n) = 0 - seq = seq[:len(seq)-1] - - while m in range(row) : - while n in range(col) : - if dfs(m, n, "") : + for m in range(row): + for n in range(col): + if dfs(m, n, 0): return True - visit.clear() return False