Skip to content

Commit e44814c

Browse files
authored
Merge branch 'DaleStudy:main' into main
2 parents ebb5f61 + c9fe566 commit e44814c

File tree

30 files changed

+1064
-0
lines changed

30 files changed

+1064
-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/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
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/

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)
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
"""
2+
271. Encode and Decode Strings
3+
https://leetcode.com/problems/encode-and-decode-strings/description/
4+
5+
Solution:
6+
- Concatenate the strings with a special character
7+
- Split the string by the special character
8+
9+
Time complexity: O(n)
10+
- Concatenating the strings: O(n)
11+
- Splitting the string: O(n)
12+
- Total: O(n)
13+
14+
Space complexity: O(n)
15+
- Storing the output: O(n)
16+
- Total: O(n)
17+
"""
18+
from typing import List
19+
20+
21+
class Codec:
22+
def encode(self, strs: List[str]) -> str:
23+
"""Encodes a list of strings to a single string."""
24+
output = strs[0]
25+
26+
for i in range(1, len(strs)):
27+
output += "é" + strs[i]
28+
29+
return output
30+
31+
def decode(self, s: str) -> List[str]:
32+
"""Decodes a single string to a list of strings."""
33+
34+
return s.split("é")

encode-and-decode-strings/evan.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
const DELIMITER = "#";
2+
3+
/**
4+
*
5+
* @param {string[]} strs
6+
* @returns {string}
7+
*/
8+
function encode(strs) {
9+
return strs.map((s) => `${s.length}${DELIMITER}${s}`).join("");
10+
}
11+
12+
/**
13+
*
14+
* @param {string} encodedStr
15+
* @returns {string[]}
16+
*/
17+
function decode(encodedStr) {
18+
const decodedStrings = [];
19+
let currentIndex = 0;
20+
21+
while (currentIndex < encodedStr.length) {
22+
let delimiterIndex = currentIndex;
23+
24+
while (encodedStr[delimiterIndex] !== DELIMITER) {
25+
delimiterIndex += 1;
26+
}
27+
28+
const strLength = parseInt(
29+
encodedStr.substring(currentIndex, delimiterIndex)
30+
);
31+
32+
decodedStrings.push(
33+
encodedStr.substring(delimiterIndex + 1, delimiterIndex + 1 + strLength)
34+
);
35+
36+
currentIndex = delimiterIndex + 1 + strLength;
37+
}
38+
39+
return decodedStrings;
40+
}
41+
/**
42+
* Time Complexity: O(n) where n is the length of the encoded string.
43+
* Reason:
44+
* The inner operations (finding # and extracting substrings) are proportional to the size of the encoded segments
45+
* but are ultimately bounded by the total length of the input string.
46+
*
47+
* Space Complexity: O(k) where k is the total length of the decoded strings.
48+
*/
49+
50+
/**
51+
* Test cases
52+
*/
53+
const strs4 = ["longestword", "short", "mid", "tiny"];
54+
const encoded4 = encode(strs4);
55+
console.log(encoded4); // Output: "11#longestword5#short3#mid4#tiny"
56+
57+
const decoded4 = decode(encoded4);
58+
console.log(decoded4); // Output: ["longestword", "short", "mid", "tiny"]

0 commit comments

Comments
 (0)