Skip to content

Commit 2dc75f9

Browse files
authored
Merge branch 'DaleStudy:main' into main
2 parents 1c119cf + 410ad39 commit 2dc75f9

File tree

44 files changed

+1403
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+1403
-0
lines changed

3sum/Leo.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution:
2+
def threeSum(self, nums: List[int]) -> List[List[int]]:
3+
4+
nums.sort()
5+
res = []
6+
7+
for i, ch in enumerate(nums):
8+
if i > 0 and nums[i] == nums[i - 1]: continue
9+
10+
l, r = i + 1, len(nums) - 1
11+
while l < r:
12+
threeSum = ch + nums[l] + nums[r]
13+
14+
if threeSum < 0:
15+
l += 1
16+
elif threeSum > 0:
17+
r -= 1
18+
else:
19+
res.append([ch, nums[l], nums[r]])
20+
l += 1
21+
while l < r and nums[l] == nums[l - 1]:
22+
l += 1
23+
24+
return res
25+
26+
## TC: O(n^2), SC: O(1)

3sum/WhiteHyun.swift

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
//
2+
// 15. 3Sum
3+
// https://leetcode.com/problems/3sum/description/
4+
// Dale-Study
5+
//
6+
// Created by WhiteHyun on 2024/06/04.
7+
//
8+
9+
class Solution {
10+
func threeSum(_ nums: [Int]) -> [[Int]] {
11+
var result: [[Int]] = []
12+
let sorted = nums.sorted()
13+
14+
for (index, element) in sorted.enumerated() where index <= 0 || element != sorted[index - 1] {
15+
var left = index + 1
16+
var right = sorted.count - 1
17+
18+
while left < right {
19+
let threeSum = element + sorted[left] + sorted[right]
20+
if threeSum > 0 {
21+
right -= 1
22+
continue
23+
}
24+
if threeSum < 0 {
25+
left += 1
26+
continue
27+
}
28+
29+
result.append([element, sorted[left], sorted[right]])
30+
left += 1
31+
32+
while sorted[left] == sorted[left - 1] && left < right {
33+
left += 1
34+
}
35+
}
36+
}
37+
38+
39+
return result
40+
}
41+
}

3sum/bhyun-kim.py

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
"""
2+
15. 3Sum
3+
https://leetcode.com/problems/3sum/description/
4+
5+
Solution:
6+
- Sort the list
7+
- Iterate through the list
8+
- For each element, find the two elements that sum up to -element
9+
- Use two pointers to find the two elements
10+
- Skip the element if it is the same as the previous element
11+
- Skip the two elements if they are the same as the previous two elements
12+
- Add the set to the output list
13+
14+
Example:
15+
-----------------------------------------
16+
low : |
17+
high: |
18+
i : |
19+
[-4,-1,-1,0,1,2]
20+
21+
-----------------------------------------
22+
low : |
23+
high: |
24+
i : |
25+
[-4,-1,-1,0,1,2]
26+
27+
... no possible set with i=-4, and high=2
28+
29+
-----------------------------------------
30+
low : |
31+
high: |
32+
i : |
33+
[-4,-1,-1,0,1,2]
34+
35+
36+
Time complexity: O(n^2)
37+
- O(nlogn) for sorting
38+
- O(n^2) for iterating through the list and finding the two elements
39+
- Total: O(n^2)
40+
Space complexity: O(n)
41+
- O(n) for the output list
42+
- O(n) for the prevs dictionary
43+
- O(n) for the prevs_n set
44+
- Total: O(n)
45+
"""
46+
47+
48+
from typing import List
49+
50+
51+
class Solution:
52+
def threeSum(self, nums: List[int]) -> List[List[int]]:
53+
nums = sorted(nums)
54+
output = []
55+
prevs = dict()
56+
prevs_n = set()
57+
58+
for i in range(len(nums) - 2):
59+
n_i = nums[i]
60+
61+
if n_i in prevs_n:
62+
continue
63+
else:
64+
prevs_n.add(n_i)
65+
66+
low, high = i + 1, len(nums) - 1
67+
while low < high:
68+
n_low = nums[low]
69+
n_high = nums[high]
70+
if n_i + n_low + n_high == 0:
71+
if not f"[{n_i},{n_low},{n_high}]" in prevs:
72+
prevs[f"[{n_i},{n_low},{n_high}]"] = 1
73+
output.append([n_i, n_low, n_high])
74+
low += 1
75+
high -= 1
76+
77+
elif n_i + n_low + n_high < 0:
78+
low += 1
79+
80+
elif n_i + n_low + n_high > 0:
81+
high -= 1
82+
83+
return output

3sum/evan.js

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number[][]}
4+
*/
5+
var threeSum = function (nums) {
6+
const sorted = nums.sort((a, b) => a - b);
7+
const result = [];
8+
9+
for (let i = 0; i < sorted.length; i++) {
10+
const fixedNumber = sorted[i];
11+
const previousFixedNumber = sorted[i - 1];
12+
13+
if (fixedNumber === previousFixedNumber) {
14+
continue;
15+
}
16+
17+
let [leftEnd, rightEnd] = [i + 1, sorted.length - 1];
18+
19+
while (leftEnd < rightEnd) {
20+
const sum = fixedNumber + sorted[leftEnd] + sorted[rightEnd];
21+
22+
if (sum === 0) {
23+
result.push([sorted[leftEnd], sorted[rightEnd], sorted[i]]);
24+
25+
while (
26+
sorted[leftEnd + 1] === sorted[leftEnd] ||
27+
sorted[rightEnd - 1] === sorted[rightEnd]
28+
) {
29+
if (sorted[leftEnd + 1] === sorted[leftEnd]) {
30+
leftEnd += 1;
31+
}
32+
33+
if (sorted[rightEnd - 1] === sorted[rightEnd]) {
34+
rightEnd -= 1;
35+
}
36+
}
37+
38+
leftEnd += 1;
39+
rightEnd -= 1;
40+
} else if (sum < 0) {
41+
leftEnd += 1;
42+
} else {
43+
rightEnd -= 1;
44+
}
45+
}
46+
}
47+
48+
return result;
49+
};
50+
51+
/**
52+
* Time Complexity: O(n^2)
53+
* The algorithm involves sorting the input array, which takes O(n log n) time.
54+
* The main part of the algorithm consists of a loop that runs O(n) times, and within that loop, there is a two-pointer technique that runs in O(n) time.
55+
* Thus, the overall time complexity is O(n log n) + O(n^2), which simplifies to O(n^2).
56+
*
57+
* Space Complexity: O(n)
58+
* The space complexity is O(n) due to the space needed for the sorted array and the result array.
59+
* Although the sorting algorithm may require additional space, typically O(log n) for the in-place sort in JavaScript, the dominant term is O(n) for the result storage.
60+
*/

3sum/invidam.go.md

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# Intuition
2+
예전에 풀어봤던 문제였어서 접근법을 알고있었다.
3+
4+
# Approach
5+
1. 정렬을 하여 배열의 대소관계를 일정하게 한다.
6+
2. i,j,k를 설정해야 하는데, i < j < k이도록 한다.
7+
3. i는 맨 앞에서부터 순회한다.
8+
4. j는 i의 뒤부터 순회한다.
9+
5. k는 맨 뒤에서부터 순회한다.
10+
6. 세 인덱스가 가리키는 값들의 합을 비교하여 j와 k를 수정한다.
11+
12+
# Complexity
13+
- Time complexity: $$O(n^2)$$
14+
- 입력 배열의 길이 n에 대하여, `i`, `j와 k`를 순회한다.
15+
16+
- Space complexity: $$O(n)$$
17+
- 입력으로 들어온 배열의 길이 n에 대하여, 생성하는 결과 배열의 길이 역시 이와 동일하다.
18+
# Code
19+
20+
```go
21+
func update(i int, j int, k int, sum int, nums []int) (int, int) {
22+
if sum <= 0 {
23+
j++
24+
for j < len(nums) && j >= 1 && nums[j] == nums[j-1] {
25+
j++
26+
}
27+
} else {
28+
k--
29+
for k >= 0 && k+1 < len(nums) && nums[k] == nums[k+1] {
30+
k--
31+
}
32+
}
33+
34+
return j, k
35+
}
36+
37+
func threeSum(nums []int) [][]int {
38+
var triplets [][]int
39+
40+
sort.Ints(nums)
41+
for i := 0; i < len(nums); i++ {
42+
j, k := i+1, len(nums)-1
43+
44+
if i != 0 && nums[i-1] == nums[i] {
45+
continue
46+
}
47+
48+
for j < k {
49+
sum := nums[i] + nums[j] + nums[k]
50+
if sum == 0 {
51+
triplets = append(triplets, []int{nums[i], nums[j], nums[k]})
52+
}
53+
j, k = update(i, j, k, sum, nums)
54+
}
55+
}
56+
return triplets
57+
}
58+
59+
```

3sum/samthekorean.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# O(n^2) where there is nested loop.
2+
# O(1) where high and low are reused as constant values.
3+
4+
5+
class Solution:
6+
def threeSum(self, nums: List[int]) -> List[List[int]]:
7+
# Initialize a set to store unique triplets
8+
triplets = set()
9+
10+
# Sort the list to make two-pointer approach possible
11+
nums.sort()
12+
13+
# Iterate through the list, considering each element as a potential first element of a triplet
14+
for i in range(len(nums) - 2):
15+
low = i + 1
16+
high = len(nums) - 1
17+
18+
# To avoid duplicate iteration
19+
while low < high:
20+
three_sum = nums[i] + nums[low] + nums[high]
21+
22+
if three_sum < 0:
23+
low += 1
24+
elif three_sum > 0:
25+
high -= 1
26+
else:
27+
triplets.add((nums[i], nums[low], nums[high]))
28+
low += 1
29+
high -= 1

3sum/yolophg.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Time Complexity: O(n^2)
2+
// Space Complexity: O(n)
3+
4+
// Time Complexity: O(n^2)
5+
// Space Complexity: O(n)
6+
7+
var threeSum = function(nums) {
8+
nums.sort((a, b) => a - b);
9+
// create a set to store triplets.
10+
const result = new Set();
11+
12+
// loop through the array, but stop 2 elements before the end.
13+
for (let i = 0; i < nums.length - 2; i++) {
14+
// if the current element is the same as the one before it, skip it to avoid duplicates.
15+
if (i > 0 && nums[i] === nums[i - 1]) continue;
16+
17+
// create a set to keep track of the complements.
18+
const complements = new Set();
19+
// start another loop from the next element.
20+
for (let j = i + 1; j < nums.length; j++) {
21+
const complement = -nums[i] - nums[j];
22+
// check if the current number is in the set.
23+
if (complements.has(nums[j])) {
24+
// if it is, found a triplet. Add it to the result set as a sorted string to avoid duplicates.
25+
result.add(JSON.stringify([nums[i], complement, nums[j]].sort((a, b) => a - b)));
26+
} else {
27+
complements.add(complement);
28+
}
29+
}
30+
}
31+
32+
// convert set of strings back to arrays.
33+
return Array.from(result).map(triplet => JSON.parse(triplet));
34+
};

container-with-most-water/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
- 문제: https://leetcode.com/problems/container-with-most-water/
2+
- 풀이: https://www.algodale.com/problems/container-with-most-water/

counting-bits/bky373.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* https://leetcode.com/problems/counting-bits/
3+
*
4+
* time: O(n * log n)
5+
* space: O(1)
6+
*/
7+
class Solution {
8+
9+
public int[] countBits(int n) {
10+
int[] ans = new int[n + 1];
11+
for (int i = 0; i <= n; i++) {
12+
int x = i;
13+
int cnt = 0;
14+
while (x != 0) {
15+
cnt++;
16+
x &= (x - 1);
17+
}
18+
ans[i] = cnt;
19+
}
20+
return ans;
21+
}
22+
}
23+

encode-and-decode-strings/Leo.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Codec:
2+
def encode(self, strs: List[str]) -> str:
3+
"""Encodes a list of strings to a single string.
4+
"""
5+
res = ''
6+
7+
for s in strs:
8+
res += str(len(s)) + '#' + s
9+
10+
return res
11+
12+
def decode(self, s: str) -> List[str]:
13+
"""Decodes a single string to a list of strings.
14+
"""
15+
res = []
16+
17+
i = 0
18+
while i < len(s):
19+
a = s.find('#', i)
20+
length = int(s[i:a])
21+
res.append(s[a + 1:a + 1 + length])
22+
i = a + 1 + length
23+
24+
return res
25+
26+
## TC: O(n), SC:O(n),n denotes sum of all len(s)

0 commit comments

Comments
 (0)