Skip to content

Commit 7c9b6e9

Browse files
committed
Add javaScript solutions
1 parent 35f2533 commit 7c9b6e9

16 files changed

+807
-0
lines changed

javaScript/easy/twoNumberSum.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// SOLUTION 1:
2+
// O(n) time | O(n) space
3+
function twoNumberSum(array, targetSum) {
4+
let obj = {};
5+
6+
for (let x of array) {
7+
if (obj[targetSum - x]) {
8+
return [targetSum - x, x];
9+
} else {
10+
obj[x] = true;
11+
}
12+
}
13+
14+
return [];
15+
}
16+
17+
// SOLUTION 2:
18+
// O(nlog(n)) | O(1) space
19+
function twoNumberSum(array, targetSum) {
20+
let obj = {};
21+
22+
for (let x of array) {
23+
if (obj[targetSum - x]) {
24+
return [targetSum - x, x];
25+
} else {
26+
obj[x] = true;
27+
}
28+
}
29+
30+
return [];
31+
}

javaScript/hard/patternMatcher.js

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// pattern = "xxyxxy"
2+
// string = "gogopowerrangergogopowerranger"
3+
// output: ["go", "powerranger"]
4+
5+
function patternMatcher(pattern, string) {
6+
if (pattern.length > string.length) {
7+
return [];
8+
}
9+
10+
const newPattern = getNewPattern(pattern);
11+
const hasPatternSwitched = pattern[0] !== newPattern[0];
12+
13+
const counts = { x: 0, y: 0 };
14+
15+
const firstYIndex = getCountsAndFirstYIndex(newPattern, counts);
16+
17+
if (counts.y !== 0) {
18+
for (let lengOfX = 1; lengOfX <= string.length; lengOfX++) {
19+
const lengOfY = (string.length - lengOfX * counts.x) / counts.y;
20+
if (lengOfY <= 0 || lengOfY % 1 !== 0) {
21+
continue;
22+
}
23+
24+
const x = string.slice(0, lengOfX);
25+
const yPosition = firstYIndex * lengOfX;
26+
const y = string.slice(yPosition, yPosition + lengOfY);
27+
28+
const potentialMatch = newPattern
29+
.map((char) => (char === 'x' ? x : y))
30+
.join('');
31+
if (potentialMatch === string) {
32+
return hasPatternSwitched ? [y, x] : [x, y];
33+
}
34+
}
35+
} else {
36+
const lengOfX = string.length / counts.x;
37+
if (lengOfX % 1 !== 0) {
38+
return [];
39+
}
40+
41+
const x = string.slice(0, lengOfX);
42+
43+
const potentialMatch = newPattern.map(() => x).join('');
44+
45+
if (potentialMatch === string) {
46+
return hasPatternSwitched ? ['', x] : [x, ''];
47+
}
48+
}
49+
50+
return [];
51+
}
52+
53+
function getNewPattern(pattern) {
54+
let patternArray = pattern.split('');
55+
if (patternArray[0] === 'x') {
56+
return patternArray;
57+
}
58+
59+
return patternArray.map((item) => (item === 'x' ? 'y' : 'x'));
60+
}
61+
62+
function getCountsAndFirstYIndex(newPattern, counts) {
63+
let firstYIndex = null;
64+
newPattern.map((item, i) => {
65+
if (item === 'y' && firstYIndex === null) {
66+
firstYIndex = i;
67+
}
68+
69+
counts[item]++;
70+
});
71+
72+
return firstYIndex;
73+
}
74+
75+
const result = patternMatcher('xxyxxy', 'gogopowerrangergogopowerranger');
76+
console.log(result);

javaScript/hard/solveSudoku.js

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
function solveSudoku(board) {
2+
// Write your code here.
3+
solveSudokuPartial(board, 0, 0);
4+
return board;
5+
}
6+
7+
function solveSudokuPartial(board, row, col) {
8+
let currentRow = row;
9+
let currentCol = col;
10+
11+
if (currentCol === board[currentRow].length) {
12+
currentRow++;
13+
currentCol = 0;
14+
15+
if (currentRow === board.length) return true;
16+
}
17+
18+
if (board[currentRow][currentCol] === 0) {
19+
return trialAllDigits(board, currentRow, currentCol);
20+
}
21+
22+
return solveSudokuPartial(board, currentRow, currentCol + 1);
23+
}
24+
25+
function trialAllDigits(board, row, col) {
26+
for (let digit = 1; digit < 10; digit++) {
27+
if (isNumberValidAtPosition(board, row, col, digit)) {
28+
board[row][col] = digit;
29+
if (solveSudokuPartial(board, row, col + 1)) return true;
30+
}
31+
}
32+
33+
board[row][col] = 0;
34+
return false;
35+
}
36+
37+
function isNumberValidAtPosition(board, row, col, value) {
38+
return !(
39+
hasNumberInRow(board, row, value) ||
40+
hasNumberInCol(board, col, value) ||
41+
hasNumberInBox(board, row, col, value)
42+
);
43+
}
44+
45+
function hasNumberInRow(board, row, value) {
46+
return board[row].includes(value);
47+
}
48+
49+
function hasNumberInCol(board, col, value) {
50+
return board.map((r) => r[col]).includes(value);
51+
}
52+
53+
function hasNumberInBox(board, row, col, value) {
54+
const rowStart = Math.floor(row / 3) * 3;
55+
const colStart = Math.floor(col / 3) * 3;
56+
57+
for (let rowIdx = 0; rowIdx < 3; rowIdx++) {
58+
for (let colIdx = 0; colIdx < 3; colIdx++) {
59+
const rowToCheck = rowStart + rowIdx;
60+
const colToCheck = colStart + colIdx;
61+
const currentValue = board[rowToCheck][colToCheck];
62+
if (currentValue === value) return true;
63+
}
64+
}
65+
66+
return false;
67+
}
68+
// Do not edit the line below.
69+
exports.solveSudoku = solveSudoku;

javaScript/medium/KadanesAlgorithm.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Write a function that takes in a non-empty array of integers and returns the
2+
// maximum sum that can be obtained by summing up all of the integers in a
3+
// non-empty subarray of the input array. A subarray must only contain adjacent
4+
// numbers (numbers next to each other in the input array).
5+
6+
// Sample input = [3, 5, -9, 1, 3, -2, 3, 4, 7, 2, -9, 6, 3, 1, -5, 4]
7+
// Sample output = 19 // [1, 3, -2, 3, 4, 7, 2, -9, 6, 3, 1]
8+
9+
function kadanesAlgorithm(array) {
10+
let maxEndingHere = array[0];
11+
let maxSoFar = array[0];
12+
13+
for (let i = 1; i < array.length; i++) {
14+
const num = array[i];
15+
maxEndingHere = Math.max(maxEndingHere + num, num);
16+
maxSoFar = Math.max(maxSoFar, maxEndingHere);
17+
}
18+
19+
return maxSoFar;
20+
}
21+
22+
const input = [3, 5, -9, 1, 3, -2, 3, 4, 7, 2, -9, 6, 3, 1, -5, 4];
23+
const result = kadanesAlgorithm(input);
24+
console.log(result); // 19
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Space Complexity O(h), where h is the height of the tree
2+
// Time Complexity O(n), where n is the number of nodes in the Binary tree
3+
class BinaryTree {
4+
constructor(value) {
5+
this.value = value;
6+
this.left = null;
7+
this.right = null;
8+
}
9+
}
10+
11+
function binaryTreeDiameter(tree) {
12+
// Write your code here.
13+
let diameter = 0;
14+
function dfsHeightCalculation(node) {
15+
if (!node) {
16+
return 0;
17+
}
18+
19+
const leftHeight = dfsHeightCalculation(node.left, diameter);
20+
const rightHeight = dfsHeightCalculation(node.right, diameter);
21+
22+
diameter = Math.max(diameter, leftHeight + rightHeight);
23+
24+
return 1 + Math.max(leftHeight, rightHeight);
25+
}
26+
27+
dfsHeightCalculation(tree);
28+
29+
return diameter;
30+
}

javaScript/medium/bstTraversal.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// O(n) time | O(n) space
2+
3+
// 10
4+
// 5 15
5+
// 2 5 22
6+
// 1
7+
8+
function inOrderTraverse(tree, array) {
9+
// [1, 2, 5, 5, 10, 15, 22]
10+
if (tree !== null) {
11+
inOrderTraverse(tree.left, array);
12+
array.push(tree.value);
13+
inOrderTraverse(tree.right, array);
14+
}
15+
return array;
16+
}
17+
18+
function preOrderTraverse(tree, array) {
19+
// [10, 5, 2, 1, 5, 15, 22]
20+
if (tree !== null) {
21+
array.push(tree.value);
22+
preOrderTraverse(tree.left, array);
23+
preOrderTraverse(tree.right, array);
24+
}
25+
return array;
26+
}
27+
28+
function postOrderTraverse(tree, array) {
29+
// [1, 2, 5, 5, 22, 15, 10]
30+
if (tree !== null) {
31+
postOrderTraverse(tree.left, array);
32+
postOrderTraverse(tree.right, array);
33+
array.push(tree.value);
34+
}
35+
return array;
36+
}

javaScript/medium/invertBinaryTree.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
function invertBinaryTree(tree) {
2+
// Write your code here.
3+
if (!tree) {
4+
return;
5+
}
6+
7+
swapLeftAndRight(tree);
8+
invertBinaryTree(tree.left);
9+
invertBinaryTree(tree.right);
10+
11+
return tree;
12+
}
13+
14+
function swapLeftAndRight(tree) {
15+
let tempNode = tree.left;
16+
tree.left = tree.right;
17+
tree.right = tempNode;
18+
}
19+
20+
// This is the class of the input binary tree.
21+
class BinaryTree {
22+
constructor(value) {
23+
this.value = value;
24+
this.left = null;
25+
this.right = null;
26+
}
27+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
class BST {
2+
constructor(value) {
3+
this.value = value;
4+
this.left = null;
5+
this.right = null;
6+
}
7+
}
8+
9+
// Solution 1:
10+
// O(n) time O(n) space
11+
function findKthLargestValueInBst(tree, k) {
12+
const sortedNodeValues = [];
13+
inorderTraverse(tree, sortedNodeValues);
14+
return sortedNodeValues[sortedNodeValues.length - k];
15+
}
16+
17+
function inorderTraverse(node, sortedNodeValues) {
18+
if (node === null) return;
19+
20+
inorderTraverse(node.left, sortedNodeValues);
21+
sortedNodeValues.push(node.value);
22+
inorderTraverse(node.right, sortedNodeValues);
23+
}
24+
25+
// Solution 2:
26+
// O(h + k) time | O(h) space - where h is the height of the tree and k is the input parameter
27+
28+
class TreeInfo {
29+
constructor(numberOfNodesVisited, latestVisitedValue) {
30+
this.numberOfNodesVisited = numberOfNodesVisited;
31+
this.latestVisitedValue = latestVisitedValue;
32+
}
33+
}
34+
35+
function findKthLargestValueInBst2(tree, k) {
36+
// Write your code here.
37+
const treeInfo = new TreeInfo(0, -1);
38+
reverseInorderTraverse(tree, treeInfo, k);
39+
return treeInfo.latestVisitedValue;
40+
}
41+
42+
function reverseInorderTraverse(node, treeInfo, k) {
43+
if (node === null || treeInfo.numberOfNodesVisited >= k) {
44+
return;
45+
}
46+
reverseInorderTraverse(node.right, treeInfo, k);
47+
if (treeInfo.numberOfNodesVisited < k) {
48+
treeInfo.numberOfNodesVisited += 1;
49+
treeInfo.latestVisitedValue = node.value;
50+
51+
reverseInorderTraverse(node.left, treeInfo, k);
52+
}
53+
}
54+
55+
// Do not edit the lines below.
56+
exports.BST = BST;
57+
exports.findKthLargestValueInBst = findKthLargestValueInBst;

0 commit comments

Comments
 (0)