Skip to content
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

Javascript solutions #11

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
31 changes: 31 additions & 0 deletions javaScript/easy/twoNumberSum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// SOLUTION 1:
// O(n) time | O(n) space
function twoNumberSum(array, targetSum) {
let obj = {};

for (let x of array) {
if (obj[targetSum - x]) {
return [targetSum - x, x];
} else {
obj[x] = true;
}
}

return [];
}

// SOLUTION 2:
// O(nlog(n)) | O(1) space
function twoNumberSum(array, targetSum) {
let obj = {};

for (let x of array) {
if (obj[targetSum - x]) {
return [targetSum - x, x];
} else {
obj[x] = true;
}
}

return [];
}
76 changes: 76 additions & 0 deletions javaScript/hard/patternMatcher.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// pattern = "xxyxxy"
// string = "gogopowerrangergogopowerranger"
// output: ["go", "powerranger"]

function patternMatcher(pattern, string) {
if (pattern.length > string.length) {
return [];
}

const newPattern = getNewPattern(pattern);
const hasPatternSwitched = pattern[0] !== newPattern[0];

const counts = { x: 0, y: 0 };

const firstYIndex = getCountsAndFirstYIndex(newPattern, counts);

if (counts.y !== 0) {
for (let lengOfX = 1; lengOfX <= string.length; lengOfX++) {
const lengOfY = (string.length - lengOfX * counts.x) / counts.y;
if (lengOfY <= 0 || lengOfY % 1 !== 0) {
continue;
}

const x = string.slice(0, lengOfX);
const yPosition = firstYIndex * lengOfX;
const y = string.slice(yPosition, yPosition + lengOfY);

const potentialMatch = newPattern
.map((char) => (char === 'x' ? x : y))
.join('');
if (potentialMatch === string) {
return hasPatternSwitched ? [y, x] : [x, y];
}
}
} else {
const lengOfX = string.length / counts.x;
if (lengOfX % 1 !== 0) {
return [];
}

const x = string.slice(0, lengOfX);

const potentialMatch = newPattern.map(() => x).join('');

if (potentialMatch === string) {
return hasPatternSwitched ? ['', x] : [x, ''];
}
}

return [];
}

function getNewPattern(pattern) {
let patternArray = pattern.split('');
if (patternArray[0] === 'x') {
return patternArray;
}

return patternArray.map((item) => (item === 'x' ? 'y' : 'x'));
}

function getCountsAndFirstYIndex(newPattern, counts) {
let firstYIndex = null;
newPattern.map((item, i) => {
if (item === 'y' && firstYIndex === null) {
firstYIndex = i;
}

counts[item]++;
});

return firstYIndex;
}

const result = patternMatcher('xxyxxy', 'gogopowerrangergogopowerranger');
console.log(result);
69 changes: 69 additions & 0 deletions javaScript/hard/solveSudoku.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
function solveSudoku(board) {
// Write your code here.
solveSudokuPartial(board, 0, 0);
return board;
}

function solveSudokuPartial(board, row, col) {
let currentRow = row;
let currentCol = col;

if (currentCol === board[currentRow].length) {
currentRow++;
currentCol = 0;

if (currentRow === board.length) return true;
}

if (board[currentRow][currentCol] === 0) {
return trialAllDigits(board, currentRow, currentCol);
}

return solveSudokuPartial(board, currentRow, currentCol + 1);
}

function trialAllDigits(board, row, col) {
for (let digit = 1; digit < 10; digit++) {
if (isNumberValidAtPosition(board, row, col, digit)) {
board[row][col] = digit;
if (solveSudokuPartial(board, row, col + 1)) return true;
}
}

board[row][col] = 0;
return false;
}

function isNumberValidAtPosition(board, row, col, value) {
return !(
hasNumberInRow(board, row, value) ||
hasNumberInCol(board, col, value) ||
hasNumberInBox(board, row, col, value)
);
}

function hasNumberInRow(board, row, value) {
return board[row].includes(value);
}

function hasNumberInCol(board, col, value) {
return board.map((r) => r[col]).includes(value);
}

function hasNumberInBox(board, row, col, value) {
const rowStart = Math.floor(row / 3) * 3;
const colStart = Math.floor(col / 3) * 3;

for (let rowIdx = 0; rowIdx < 3; rowIdx++) {
for (let colIdx = 0; colIdx < 3; colIdx++) {
const rowToCheck = rowStart + rowIdx;
const colToCheck = colStart + colIdx;
const currentValue = board[rowToCheck][colToCheck];
if (currentValue === value) return true;
}
}

return false;
}
// Do not edit the line below.
exports.solveSudoku = solveSudoku;
24 changes: 24 additions & 0 deletions javaScript/medium/KadanesAlgorithm.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Write a function that takes in a non-empty array of integers and returns the
// maximum sum that can be obtained by summing up all of the integers in a
// non-empty subarray of the input array. A subarray must only contain adjacent
// numbers (numbers next to each other in the input array).

// Sample input = [3, 5, -9, 1, 3, -2, 3, 4, 7, 2, -9, 6, 3, 1, -5, 4]
// Sample output = 19 // [1, 3, -2, 3, 4, 7, 2, -9, 6, 3, 1]

function kadanesAlgorithm(array) {
let maxEndingHere = array[0];
let maxSoFar = array[0];

for (let i = 1; i < array.length; i++) {
const num = array[i];
maxEndingHere = Math.max(maxEndingHere + num, num);
maxSoFar = Math.max(maxSoFar, maxEndingHere);
}

return maxSoFar;
}

const input = [3, 5, -9, 1, 3, -2, 3, 4, 7, 2, -9, 6, 3, 1, -5, 4];
const result = kadanesAlgorithm(input);
console.log(result); // 19
30 changes: 30 additions & 0 deletions javaScript/medium/binaryTreeDiameter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Space Complexity O(h), where h is the height of the tree
// Time Complexity O(n), where n is the number of nodes in the Binary tree
class BinaryTree {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}

function binaryTreeDiameter(tree) {
// Write your code here.
let diameter = 0;
function dfsHeightCalculation(node) {
if (!node) {
return 0;
}

const leftHeight = dfsHeightCalculation(node.left, diameter);
const rightHeight = dfsHeightCalculation(node.right, diameter);

diameter = Math.max(diameter, leftHeight + rightHeight);

return 1 + Math.max(leftHeight, rightHeight);
}

dfsHeightCalculation(tree);

return diameter;
}
36 changes: 36 additions & 0 deletions javaScript/medium/bstTraversal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// O(n) time | O(n) space

// 10
// 5 15
// 2 5 22
// 1

function inOrderTraverse(tree, array) {
// [1, 2, 5, 5, 10, 15, 22]
if (tree !== null) {
inOrderTraverse(tree.left, array);
array.push(tree.value);
inOrderTraverse(tree.right, array);
}
return array;
}

function preOrderTraverse(tree, array) {
// [10, 5, 2, 1, 5, 15, 22]
if (tree !== null) {
array.push(tree.value);
preOrderTraverse(tree.left, array);
preOrderTraverse(tree.right, array);
}
return array;
}

function postOrderTraverse(tree, array) {
// [1, 2, 5, 5, 22, 15, 10]
if (tree !== null) {
postOrderTraverse(tree.left, array);
postOrderTraverse(tree.right, array);
array.push(tree.value);
}
return array;
}
27 changes: 27 additions & 0 deletions javaScript/medium/invertBinaryTree.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
function invertBinaryTree(tree) {
// Write your code here.
if (!tree) {
return;
}

swapLeftAndRight(tree);
invertBinaryTree(tree.left);
invertBinaryTree(tree.right);

return tree;
}

function swapLeftAndRight(tree) {
let tempNode = tree.left;
tree.left = tree.right;
tree.right = tempNode;
}

// This is the class of the input binary tree.
class BinaryTree {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
57 changes: 57 additions & 0 deletions javaScript/medium/kthLargestValueBST.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
class BST {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}

// Solution 1:
// O(n) time O(n) space
function findKthLargestValueInBst(tree, k) {
const sortedNodeValues = [];
inorderTraverse(tree, sortedNodeValues);
return sortedNodeValues[sortedNodeValues.length - k];
}

function inorderTraverse(node, sortedNodeValues) {
if (node === null) return;

inorderTraverse(node.left, sortedNodeValues);
sortedNodeValues.push(node.value);
inorderTraverse(node.right, sortedNodeValues);
}

// Solution 2:
// O(h + k) time | O(h) space - where h is the height of the tree and k is the input parameter

class TreeInfo {
constructor(numberOfNodesVisited, latestVisitedValue) {
this.numberOfNodesVisited = numberOfNodesVisited;
this.latestVisitedValue = latestVisitedValue;
}
}

function findKthLargestValueInBst2(tree, k) {
// Write your code here.
const treeInfo = new TreeInfo(0, -1);
reverseInorderTraverse(tree, treeInfo, k);
return treeInfo.latestVisitedValue;
}

function reverseInorderTraverse(node, treeInfo, k) {
if (node === null || treeInfo.numberOfNodesVisited >= k) {
return;
}
reverseInorderTraverse(node.right, treeInfo, k);
if (treeInfo.numberOfNodesVisited < k) {
treeInfo.numberOfNodesVisited += 1;
treeInfo.latestVisitedValue = node.value;

reverseInorderTraverse(node.left, treeInfo, k);
}
}

// Do not edit the lines below.
exports.BST = BST;
exports.findKthLargestValueInBst = findKthLargestValueInBst;
Loading
Oops, something went wrong.