Skip to content

Instantly share code, notes, and snippets.

View optimistiks's full-sized avatar

Max optimistiks

View GitHub Profile
@optimistiks
optimistiks / jump-game.js
Created May 24, 2023 22:21
You’ve been provided with the nums integer array, representing the series of squares. You’re initially positioned at the first index of the array. Find the minimum number of jumps needed to reach the last index of the array. You may assume that you can always reach the last index.
export function jumpGameTwo(nums) {
if (nums.length === 1) {
return 0;
}
// our current position in the array
let current = 0;
// the farthest index that is reachable from elements iterated up until now
let farthest = 0;
// number of jumps done
@optimistiks
optimistiks / 1-n-queens.js
Created June 14, 2023 13:11
Given a chessboard of size n×n, determine how many ways n queens can be placed on the board, such that no two queens attack each other.
// to check diagonals,
// row - col for neg diag,
// row + col for pos diag,
// those values will remain constant along the whole diagonal
function canPlace(row, col, result) {
for (let boardRow = 0; boardRow < row; ++boardRow) {
const boardCol = result[boardRow];
if (col === boardCol) {
// col is taken
return false;
@optimistiks
optimistiks / word-search.js
Created June 15, 2023 12:58
Given an m×n 2D grid of characters and word as a string, we need to determine if the word can be constructed from letters of sequentially adjacent cells. The cells are considered sequentially adjacent when they are neighbors to each other either horizontally or vertically. The function should return TRUE if the word can be constructed and FALSE …
export function wordSearch(grid, word) {
for (let row = 0; row < grid.length; ++row) {
for (let col = 0; col < grid[row].length; ++col) {
const result = wordSearchRec(grid, word, row, col, 0);
if (result) {
return true;
}
}
}
return false;
@optimistiks
optimistiks / 1-house-robber.js
Last active July 5, 2023 16:09
House Robber III
export function rob(root) {
const result = robRec(root);
return Math.max(...result);
}
function robRec(node) {
if (!node.left && !node.right) {
return [node.data, 0];
}
const [includingRootLeft, excludingRootLeft] = node.left
@optimistiks
optimistiks / restore-ip.js
Created July 5, 2023 23:04
Given that a string, s, contains digits, return a list of all possible valid IP addresses that can be obtained from the string. 4 <= s.length <= 12
export function restoreIpAddresses(s) {
const addresses = [];
const segments = [];
restoreIpRec(s, 0, 3, segments, addresses);
return addresses;
}
function restoreIpRec(s, pos, dots, segments, addresses) {
if (dots === 0) {
// base case, dots === 0 meaning there are no dots left to place
@optimistiks
optimistiks / sudoku.js
Last active July 6, 2023 21:09
Given a 9 x 9 sudoku board, solve the puzzle by completing the empty cells.
let DIGITS = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];
export function solveSudoku(board) {
const sets = createSets();
const emptyCells = [];
// iterate board, add empty cells to the list of empty cells,
// add values of nonempty cells to row, col and subbox sets,
// so we can later check if value present in a row / col / subbox
// by checking the corresponding set
for (let row = 0; row < board.length; ++row) {
@optimistiks
optimistiks / flood-fill.js
Created July 6, 2023 22:02
Our task is to perform flood fill by updating the values of the four directionally connected cells, which have the same value as the source cell with the target value.
function floodFill(grid, sr, sc, target) {
// last argument is the original value that was in the source cell
// (which is the value that an adjacent cell must have for the fill to continue)
// since its our first call we pass null
// so this value can be initialized
floodFillRec(grid, sr, sc, target, null)
return grid
}
function floodFillRec(grid, sr, sc, target, prevV) {
@optimistiks
optimistiks / matchstick-square.js
Created July 7, 2023 00:18
Given an integer array, matchsticks, where matchsticks[i] is the length of the ith matchstick. Use every single matchstick to create a square. No stick should be broken, although they can be connected, and each matchstick can only be used once.
export function matchstickToSquare(matchsticks) {
// find total sum of matchsticks lengths
const sum = matchsticks.reduce((sum, len) => sum + len, 0);
// if sum cant be divided by 4 or there are less than 4 matchsticks, not possible
if (sum % 4 !== 0 || matchsticks.length < 4) {
return false;
}
// target is our square side length
const target = sum / 4;
// initialize sides lengths with zeros
@optimistiks
optimistiks / zero-one-knapsack.js
Created July 8, 2023 00:01
You are given n items whose weights and values are known, as well as a knapsack to carry these items. The knapsack cannot carry more than a certain maximum weight, known as its capacity. You need to maximize the total value of the items in your knapsack, while ensuring that the sum of the weights of the selected items does not exceed the capacit…
export function findMaxKnapsackProfit(capacity, weights, values) {
// a single array version,
// it's an optimized two-array version (repeatedly swap two arrays to hold previous and current row)
// which is in itself an optimized 2d array solution
const dp = Array(capacity + 1).fill(0);
// first we build an array of solutions for each possible capacity with only the first item considered
// then we update the array by considering the second item
// after that array contains optimal solutions with both items considered, so we can move to third, and so on
for (let item = 0; item < weights.length; ++item) {
@optimistiks
optimistiks / coin-change.js
Created July 8, 2023 23:03
You're given an integer total and a list of integers called coins. The variable coins hold a list of coin denominations, and total is the total amount of money. You have to find the minimum number of coins that can make up the total amount by using any combination of the coins.
export function coinChange(coins, total) {
// we make a total + 1 counter,
// so later when we need to "ask" this array for a subproblem solution
// it will look more natural, counter[total] (give me solution for total),
// instead of doing -1 every time for index offset (counter[total-1])
const counter = Array(total + 1).fill(null);
// your code will replace this placeholder return statement
return coinsChangeRec(coins, total, counter);
}