Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions longest-substring-without-repeating-characters/hyer0705.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
function lengthOfLongestSubstring(s: string): number {
let maxLen = 0;

const used = new Set<string>();
let windowStart = 0;

for (let windowEnd = 0; windowEnd < s.length; windowEnd++) {
const currentCh = s[windowEnd];
while (used.has(currentCh)) {
used.delete(s[windowStart]);
windowStart++;
}

used.add(currentCh);
maxLen = Math.max(maxLen, windowEnd - windowStart + 1);
}

return maxLen;
Comment on lines +15 to +18
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

첨언할 게 없게 잘 짜셔서 이거라도 써봅니다.
maxLen0 대신 -1로 초기화하면 다음과 같이 덧셈 연산 반복을 줄일 수 있겠어요:

Suggested change
maxLen = Math.max(maxLen, windowEnd - windowStart + 1);
}
return maxLen;
maxLen = Math.max(maxLen, windowEnd - windowStart);
}
return maxLen + 1;

}
52 changes: 52 additions & 0 deletions number-of-islands/hyer0705.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
function numIslands(grid: string[][]): number {
const m = grid.length;
const n = grid[0].length;

const LAND = "1";
const WATER = "0";

const visited: boolean[][] = Array.from({ length: m }, () => Array(n).fill(false));

const isValid = (row: number, col: number): boolean => row >= 0 && row < m && col >= 0 && col < n;

const bfs = (row: number, col: number): void => {
const directions = [
[0, 1],
[0, -1],
[1, 0],
[-1, 0],
];

// [row, col][]
const queue: number[][] = [];

visited[row][col] = true;
queue.push([row, col]);

while (queue.length > 0) {
const [cx, cy] = queue.shift()!;
Comment on lines +26 to +27
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Array.prototype.shift()의 시간 복잡도는 선형 O(n)이 아닌가요?
그래서 다음과 같이 고쳐 주셔야 시간 복잡도가 O(n^2)이 되는 일을 피할 수 있지 않을까요?

Suggested change
while (queue.length > 0) {
const [cx, cy] = queue.shift()!;
let head = 0;
while (head !== queue.length) {
const [cx, cy] = queue[head++];

그리고 혹시 shift!는 어떤 효과가 있나요?
그런데 shift로 시간이 초과하기는커녕 거의 차이가 없는 것이 매우 신기해요.
이유를 아시는 분이 계시다면 알려 주세요!
제가 브라우저에서 실험해 보니 이렇게 나와요.

const n = 100000;

let arr;
let start, end;
let x;

arr = Array(n).fill(1);
x = 0;
start = Date.now();
for (let i = 0; i < n; i++) {
    x += arr.shift();
}
end = Date.now();
console.log('shift:', end - start, 'ms, x:', x);

arr = Array(n).fill(1);
y = 0;
start = Date.now();
let front = 0;
for (let i = 0; i < n; i++) {
    y += arr[front++]
}
end = Date.now();
console.log('front:', end - start, 'ms, y:', y);

// shift: 3273 ms, x: 100000
// front: 2 ms, y: 100000

Copy link
Contributor Author

@hyer0705 hyer0705 Sep 6, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

긴 코멘트 감사합니다! 제 코드에서 개선할 점도 알게 되고 저도 고민해볼 거리가 생긴거 같네요! 질문 남기신 것 중에 제가 답변해드릴 수 있는 부분은 아래와 같이 정리를 해봤습니다.

평소에 그냥 Array.prototype.shift() 메서드를 쓰는거에 익숙해서 일단은 풀어서 정답이 나오면 바로 넘어가서 이런 코드가 남겨진거 같네요! 다음엔 말씀해주신 방법을 사용해서 문제를 풀이해보도록 하겠습니다.

shift() 뒤에 ! 연산자의 경우, TypeScript에서 Non Null Assertion 연산자로 불리는 연산자로 해당 값은 undefined 혹은 null 값이 아니다 라는 걸 단언하는 연산자입니다. Array.prototype.shift() 메서드는 해당 메서드를 호출한 배열이 비어있는경우 undefined를 반환합니다. 저는 cx, cy에 undefined 값이 들어가지 않는다는 것을 단언하기 위해 해당 연산자를 사용했습니다. IDE에서는 해당 연산자를 쓰지 않으면 cx, cy에서 빨간 밑줄이 표시되거든요!
Non-null Assertion Operator (Postfix !) | TypeScript Documentation

shift() 메서드를 사용했는데 시간 초과가 나지 않고 정답인 이유가 궁금한게 맞을까요..? 저도 이유는 모르겠지만 테스트케이스가 시간 초과가 되지 않는 정도만 있는게 아닐까요...?

Copy link
Contributor

@yhkee0404 yhkee0404 Sep 6, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오.. 그랬군요. 반대로 Bracket으로 Property access 할 때는 undefined가 아니라 !이 필요 없을 수 있겠네요. 감사합니다!


for (const [dx, dy] of directions) {
const [nx, ny] = [cx + dx, cy + dy];

if (isValid(nx, ny) && !visited[nx][ny] && grid[nx][ny] === LAND) {
visited[nx][ny] = true;
queue.push([nx, ny]);
}
}
}
};

let island = 0;

for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === LAND && !visited[i][j]) {
island++;
bfs(i, j);
}
}
}

return island;
}
40 changes: 40 additions & 0 deletions reverse-linked-list/hyer0705.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/

// using iterative
function reverseList(head: ListNode | null): ListNode | null {
if (!head) return null;

let prev: ListNode | null = null;
let current = head;

while (current) {
const temp: ListNode | null = current.next;
current.next = prev;
prev = current;
current = temp;
}

return prev;
}

// using recursive
function reverseList(head: ListNode | null): ListNode | null {
if (!head || !head.next) return head;

const newHead = reverseList(head.next);

head.next.next = head;
head.next = null;

return newHead;
}
70 changes: 70 additions & 0 deletions set-matrix-zeroes/hyer0705.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// mark first row, first col - 0ms
/**
Do not return anything, modify matrix in-place instead.
*/
function setZeroes(matrix: number[][]): void {
const m = matrix.length;
const n = matrix[0].length;

let isFirstColZero = false;
let isFirstRowZero = false;
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (matrix[i][j] === 0) {
if (!isFirstRowZero && i === 0) isFirstRowZero = true;
if (!isFirstColZero && j === 0) isFirstColZero = true;
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}

for (let i = 1; i < m; i++) {
for (let j = 1; j < n; j++) {
if (matrix[i][0] === 0 || matrix[0][j] === 0) {
matrix[i][j] = 0;
}
}
}

if (isFirstRowZero) {
for (let j = 0; j < n; j++) {
matrix[0][j] = 0;
}
}
if (isFirstColZero) {
for (let i = 0; i < m; i++) {
matrix[i][0] = 0;
}
}
}

// using set - 4ms
/**
Do not return anything, modify matrix in-place instead.
*/
function setZeroes(matrix: number[][]): void {
const m = matrix.length;
const n = matrix[0].length;

// `${row},${col}`
const coordinates = new Set<string>();

for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (matrix[i][j] === 0) {
coordinates.add(`${i},${j}`);
}
}
}

for (const coordinate of coordinates) {
const [x, y] = coordinate.split(",");
for (let j = 0; j < n; j++) {
matrix[x][j] = 0;
}
for (let i = 0; i < m; i++) {
matrix[i][y] = 0;
}
}
}
11 changes: 11 additions & 0 deletions unique-paths/hyer0705.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
function uniquePaths(m: number, n: number): number {
const dp: number[][] = Array.from({ length: m }, () => Array(n).fill(1));

for (let i = 1; i < m; i++) {
for (let j = 1; j < n; j++) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}

return dp[m - 1][n - 1];
}