-
-
Notifications
You must be signed in to change notification settings - Fork 363
[togo26] WEEK 03 Solutions #2723
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
togo26
wants to merge
18
commits into
DaleStudy:main
Choose a base branch
from
togo26:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+256
−0
Open
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
f1e8a69
contains-duplicate solution
togo26 8d84daf
two-sum solution
togo26 858598f
top-k-frequent-elements solution
togo26 de255d3
longest-consecutive-sequence solution
togo26 1f68a57
house-robber solution
togo26 54577e5
valid-anagram solution
togo26 245a1b1
climbing-stairs solution
togo26 b71c9fa
product-of-array-except-self solution
togo26 b7af1f8
3sum solution
togo26 399b3a3
validate-binary-search-tree solution
togo26 67296f6
Merge branch 'DaleStudy:main' into main
togo26 ff613e8
Apply suggestion from @parkhojeong
togo26 a247f61
valid-palindrome solution
togo26 a272e08
number-of-1-bits solution
togo26 66d06d3
combination-sum solution
togo26 f3179e9
decode-ways solution
togo26 2821b32
maximum-subarray solution
togo26 bc0a604
Merge branch 'DaleStudy:main' into main
togo26 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| /** | ||
| * @param {number[]} candidates | ||
| * @param {number} target | ||
| * @return {number[][]} | ||
| */ | ||
|
|
||
| // C = candidates, T = target, m = smallest candidate value | ||
| // TC: O(C^(T/m)) -> 후보와 타겟 깊이 간 지수적 증가 | ||
| // SC: O(T/m) -> 재귀 스택 깊이 (*출력 결과는 복잡도 계산 제외) | ||
| var combinationSum = function (candidates, target) { | ||
| const result = []; | ||
|
|
||
| function go(candi, combi, acc, start) { | ||
| if (acc === target) { | ||
| result.push(combi); | ||
| return; | ||
| } | ||
|
|
||
| for (let i = start; i < candi.length; i++) { | ||
| const newAcc = acc + candi[i]; | ||
| const newCombi = [...combi, candi[i]]; | ||
| if (newAcc > target) break; | ||
| go(candi, newCombi, newAcc, i); | ||
| } | ||
| } | ||
|
|
||
| go( | ||
| [...candidates].sort((a, b) => a - b), // 값 순서 보장으로 새로운 누적 값에서 조기 종료 가능. 오름차순에 따라 newAcc가 target을 넘어가면 이후의 후보들은 계산할 필요 없음. | ||
| [], | ||
| 0, | ||
| 0, | ||
| ); | ||
|
|
||
| return result; | ||
| }; |
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 숫자 문자열을 한 자리/두 자리로 분리해 가짓수를 누적하는 전형적인 DP 풀이입니다. 개선 제안: 현재 구현이 적절해 보입니다. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| /** | ||
| * @param {string} s | ||
| * @return {number} | ||
| */ | ||
|
|
||
| // TLE | ||
| // var numDecodings = function(s) { | ||
| // const codeMap = {}; | ||
| // for (let i = 1; i <= 26; i++) { | ||
| // codeMap[i] = String.fromCharCode(64 + i); | ||
| // } | ||
|
|
||
| // const memo = {}; | ||
| // let count = 0; | ||
| // function go(string, start) { | ||
| // if (start >= string.length) { | ||
| // count++; | ||
| // return; | ||
| // } | ||
|
|
||
| // const firstDigit = string[start]; | ||
| // const secondDigit = string[start + 1]; | ||
| // if (firstDigit === "0") return; | ||
|
|
||
| // if (codeMap[firstDigit]) { | ||
| // go(string, start + 1); | ||
| // } | ||
|
|
||
| // const twoDigits = firstDigit + secondDigit; | ||
| // if (Number(twoDigits) <= 26 && codeMap[twoDigits]) { | ||
| // go(string, start + 2); | ||
| // } | ||
| // } | ||
|
|
||
| // go(s, 0, ""); | ||
|
|
||
| // return count; | ||
| // }; | ||
|
|
||
| // TC: O(n) -> string 길이만큼 | ||
| // SC: O(n) -> string 길이만큼 스택 생성 | ||
| var numDecodings = function (s) { | ||
| const codeMap = {}; | ||
| for (let i = 1; i <= 26; i++) { | ||
| codeMap[i] = String.fromCharCode(64 + i); | ||
| } | ||
|
|
||
| const memo = {}; | ||
|
|
||
| function go(start) { | ||
| if (start >= s.length) return 1; | ||
| if (memo[start] !== undefined) return memo[start]; | ||
|
|
||
| const firstDigit = s[start]; | ||
| const secondDigit = s[start + 1]; | ||
|
|
||
| if (firstDigit === '0') return 0; | ||
|
|
||
| let ways = 0; | ||
|
|
||
| if (codeMap[firstDigit]) { | ||
| ways += go(start + 1); | ||
| } | ||
|
|
||
| const twoDigits = firstDigit + secondDigit; | ||
| if (Number(twoDigits) <= 26 && codeMap[twoDigits]) { | ||
| ways += go(start + 2); | ||
| } | ||
|
|
||
| memo[start] = ways; | ||
|
|
||
| return ways; | ||
| } | ||
|
|
||
| return go(0); | ||
| }; |
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 현재 구현은 최적의 선형 알고리즘으로 공간도 상수이며, 음수 배열도 처리합니다. 개선 제안: 현재 구현이 적절해 보입니다. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| /** | ||
| * @param {number[]} nums | ||
| * @return {number} | ||
| */ | ||
|
|
||
| // TLE | ||
| // var maxSubArray = function(nums) { | ||
| // if (nums.length <= 1) return nums[0]; | ||
|
|
||
| // const sum = (arr) => arr.reduce((acc, cur) => { | ||
| // acc += cur; | ||
| // return acc; | ||
| // }, 0); | ||
|
|
||
| // let total = -Infinity; | ||
| // for (let i = 0; i < nums.length; i++) { | ||
| // for (let j = i; j < nums.length; j++) { | ||
| // const result = sum(nums.slice(i, j + 1)); | ||
| // total = Math.max(total, result); | ||
| // } | ||
| // } | ||
|
|
||
| // return total; | ||
| // }; | ||
|
|
||
| // TLE | ||
| // var maxSubArray = function(nums) { | ||
| // if (nums.length <= 1) return nums[0]; | ||
|
|
||
| // let total = -Infinity; | ||
| // for (let i = 0; i < nums.length; i++) { | ||
| // let acc = 0; | ||
| // for (let j = i; j < nums.length; j++) { | ||
| // acc += nums[j]; | ||
| // total = Math.max(total, acc); | ||
| // } | ||
| // } | ||
|
|
||
| // return total; | ||
| // }; | ||
|
|
||
| // TC: O(n) / SC: O(1) | ||
| var maxSubArray = function (nums) { | ||
| let total = nums[0]; | ||
| let acc = nums[0]; | ||
|
|
||
| for (let i = 1; i < nums.length; i++) { | ||
| acc = Math.max(nums[i], acc + nums[i]); // 이전 누적값 선택 vs 현재값 선택 (카데인 알고리즘) | ||
| total = Math.max(total, acc); // 최대 합산 값 갱신 | ||
| } | ||
|
|
||
| return total; | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| /** | ||
| * @param {number} n | ||
| * @return {number} | ||
| */ | ||
|
|
||
| // 31 비트 범위는 상수로 취급 | ||
|
|
||
| // Log-based calculation | ||
| // TC: O(1) / SC: O(1) | ||
| // 비트 제약이 없을 경우 -> TC: O(logn) / SC: O(logn) | ||
| var hammingWeight = function (n) { | ||
| const BIT_RANGE = 31; | ||
| let bits = Array.from({ length: BIT_RANGE }).fill(0); | ||
|
|
||
| let remainder = n; | ||
| while (remainder > 0) { | ||
| const exp = Math.min(Math.floor(Math.log2(remainder)), BIT_RANGE - 1); | ||
| bits[exp] = true; | ||
| const value = remainder <= 1 ? 1 : Math.pow(2, exp); | ||
| remainder -= value; | ||
| } | ||
|
|
||
| return bits.filter(value => value).length; | ||
| }; | ||
|
|
||
| // Log-based calculation without an array | ||
| // TC: O(1) / SC: O(1) | ||
| // 비트 제약이 없을 경우 -> TC: O(logn) / SC: O(1) | ||
| var hammingWeight = function (n) { | ||
| const BIT_RANGE = 31; | ||
| let bitCount = 0; | ||
|
|
||
| let remainder = n; | ||
| while (remainder > 0) { | ||
| const exp = Math.min(Math.floor(Math.log2(remainder)), BIT_RANGE - 1); | ||
| const value = remainder <= 1 ? 1 : Math.pow(2, exp); | ||
| remainder -= value; | ||
| bitCount++; | ||
| } | ||
|
|
||
| return bitCount; | ||
| }; | ||
|
|
||
| // Converting binary string with the JS feature | ||
| // TC: O(1) / SC: O(1) | ||
| // 비트 제약이 없을 경우 -> TC: O(logn) / SC: O(logn) | ||
| var hammingWeight = function (n) { | ||
| const binaryString = n.toString(2); | ||
| return [...binaryString].filter(v => v === '1').length; | ||
| }; | ||
|
|
||
| // Bit manipulation | ||
| // TC: O(1) / SC: O(1) | ||
| // 비트 제약이 없을 경우 -> TC: O(logn) / SC: O(logn) | ||
| var hammingWeight = function (n) { | ||
| let count = 0; | ||
|
|
||
| while (n > 0) { | ||
| n = n & (n - 1); | ||
| count++; | ||
| } | ||
|
|
||
| return count; | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| /** | ||
| * @param {string} s | ||
| * @return {boolean} | ||
| */ | ||
| // TC: O(n) / SC: O(n) | ||
| var isPalindrome = function (s) { | ||
| const processed = s.toLowerCase().replaceAll(/[^a-z0-9]+/g, ''); | ||
| const reversed = [...processed].reverse().join(''); | ||
| return processed === reversed; | ||
| }; | ||
|
|
||
| // TC: O(n) / SC: O(1) | ||
| // With two pointers | ||
| var isPalindrome = function (s) { | ||
| const nonAlphanumeric = new RegExp(/[^a-zA-Z0-9]+/); | ||
| let left = 0; | ||
| let right = s.length - 1; | ||
|
|
||
| while (left < right) { | ||
| while (left < right && nonAlphanumeric.test(s[left])) left++; // 단일 문자 테스트 O(1) 상수 취급 | ||
| while (left < right && nonAlphanumeric.test(s[right])) right--; | ||
| if (s[left].toLowerCase() !== s[right].toLowerCase()) return false; | ||
| left++; | ||
| right--; | ||
| } | ||
|
|
||
| return true; | ||
| }; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 정렬 후 탐색 트리에서 누적합이 target을 넘으면 가지를 자르도록 하여 불필요한 재귀 호출을 제거했습니다.
개선 제안: 현재 구현이 적절해 보입니다.