Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
46 changes: 46 additions & 0 deletions merge-two-sorted-lists/gwbaik9717.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// m: list1, n: list2
// Time complexity: O(m+n)
// Space complexity: O(m+n)

/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} list1
* @param {ListNode} list2
* @return {ListNode}
*/
var mergeTwoLists = function (list1, list2) {
const answer = new ListNode();
let current = answer;

while (list1 && list2) {
if (list1.val < list2.val) {
current.next = new ListNode(list1.val);
list1 = list1.next;
} else {
current.next = new ListNode(list2.val);
list2 = list2.next;
}

current = current.next;
}

while (list1) {
current.next = new ListNode(list1.val);
list1 = list1.next;
current = current.next;
}

while (list2) {
current.next = new ListNode(list2.val);
list2 = list2.next;
current = current.next;
}

return answer.next;
};
15 changes: 15 additions & 0 deletions missing-number/gwbaik9717.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Time complexity: O(n)
// Space complexity: O(1)

/**
* @param {number[]} nums
* @return {number}
*/
var missingNumber = function (nums) {
const n = nums.length;
const target = (n * (n + 1)) / 2;

const sum = nums.reduce((a, c) => a + c, 0);

return target - sum;
};
62 changes: 62 additions & 0 deletions word-search/gwbaik9717.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// h: height of the board, w: width of the board, n: length of the word
// Time complexity: O(h * w * 4**n)
// Space complexity: O(h * w + n)

/**
* @param {character[][]} board
* @param {string} word
* @return {boolean}
*/
var exist = function (board, word) {
const n = word.length;
const h = board.length;
const w = board[0].length;

const dy = [1, 0, -1, 0];
const dx = [0, 1, 0, -1];

const checked = Array.from({ length: h }, () =>
Array.from({ length: w }, () => 0)
);

let answer = false;

const dfs = (current, index) => {
if (index === n - 1) {
answer = true;
return;
}

const [cy, cx] = current;
checked[cy][cx] = 1;

for (let i = 0; i < dy.length; i++) {
const ny = cy + dy[i];
const nx = cx + dx[i];
const ni = index + 1;

if (
ny >= 0 &&
ny < h &&
nx >= 0 &&
nx < w &&
checked[ny][nx] === 0 &&
word[ni] === board[ny][nx]
) {
dfs([ny, nx], ni);
}
}

checked[cy][cx] = 0;
};

for (let i = 0; i < h; i++) {
for (let j = 0; j < w; j++) {
if (board[i][j] === word[0] && !answer) {
dfs([i, j], 0);
}
}
}

return answer;
};
Loading