Skip to content

Instantly share code, notes, and snippets.

View optimistiks's full-sized avatar

Max optimistiks

View GitHub Profile
@optimistiks
optimistiks / tribonacci.js
Last active July 8, 2023 23:40
Given a number n, calculate the corresponding Tribonacci number.
export function findTribonacci(n) {
// we use an array of fixed size so we keep a constant amount of subproblem solutions at each iteration
// therefore ensuring constant space complexity
const dp = [0, 1, 1];
if (n < 3) {
return dp[n];
}
for (let i = 3; i <= n; ++i) {
@optimistiks
optimistiks / partition-equal-subsets.js
Created July 9, 2023 23:50
Given a non-empty array of positive integers, determine if the array can be divided into two subsets so that the sum of both subsets is equal.
export function canPartitionArray(nums) {
// find sum of items
const total = nums.reduce((acc, num) => acc + num, 0);
// if there is a remainder, it's not possible to split the array in two subsets with the same sum
if (total % 2 !== 0) {
return false;
}
// get our half sum, we need to determine if there is a subset that sums up to half sum,
@optimistiks
optimistiks / counting-bits.js
Created July 11, 2023 08:53
For a given positive integer, n, your task is to return an array of length n+1 such that for each x where 0≤x≤n, result[x] is the count of 1s in the binary representation of x .
function countingBits(n) {
const dp = [0, 1];
// even numbers have their 1s count equal to count of the number / 2
// odd numbers have their 1s count equal to count of the number / 2, plus one
// for example, binary representation of 7 is 111 (count = 3)
// first we get count of 3 (floor(7 / 2)) which equals to 2 (binary = 11), and then plus one
// binary representation of 4 is 100 (count = 1)
// same as count of 2 (4/2), which is 1
@optimistiks
optimistiks / 01-matrix.js
Created July 12, 2023 18:16
Given an m×n binary matrix, mat, find the distance from each cell to the nearest 0. The distance between two adjacent cells is 1. Cells to the left, right, above, and below the current cell will be considered adjacent.
function updateMatrix(mat) {
// first iteration, from top left to bottom right
// calculate min distance of cell i,j as min distance of it's left and top neighbors + 1
// if left / top is inaccessible, use Infinity
for (let i = 0; i < mat.length; ++i) {
for (let j = 0; j < mat[i].length; ++j) {
if (mat[i][j] === 0) {
continue;
}
mat[i][j] =
@optimistiks
optimistiks / house-robber-II.js
Created July 18, 2023 21:23
A professional robber plans to rob some houses along a street. These houses are arranged in a circle, which means that the first and the last house are neighbors. The robber cannot rob adjacent houses because they have security alarms installed. Following the constraints mentioned above and given an integer array money representing the amount of…
function houseRobber(money) {
return Math.max(
calcMax(money, 0, money.length - 1),
calcMax(money, 1, money.length)
);
}
function calcMax(money, from, to) {
const dp = [];
for (let i = from; i < to; ++i) {
@optimistiks
optimistiks / max-product-subarray.js
Created July 18, 2023 22:18
Given an integer array, nums, find a subarray that has the largest product, and return the product.
export function maxProduct(nums) {
if (nums.length === 0) {
return 0;
}
// we are going to track the minimum value as well as we progress
// because we might encounter a negative value, and then another negative value
// so it's possible our minimal value will be flipped to be a positive, and a new maximum
// store here the max seen product so far
@optimistiks
optimistiks / combination-sum.js
Created July 19, 2023 00:53
Given an array of distinct integers, nums, and an integer, target, return a list of all unique combinations of nums where the chosen numbers sum up to the target. The combinations may be returned in any order. An integer from nums may be chosen an unlimited number of times.
function combinationSum(nums, target) {
// prepare a dp array
// indexes are target values up to target
// for example dp [3] contains all unique combinations that add up to 3
// so at the end we will be able to return dp[target]
const dp = Array(target + 1).fill().map(() => []);
// the only combination that sums up to 0 is an empty combination
dp[0] = [[]]
// start iterating target values, from 1 to target including
for (let subTar = 1; subTar <= target; ++subTar) {
@optimistiks
optimistiks / word-break.js
Created July 20, 2023 12:08
Given a string, s, and a dictionary of strings, wordDict, check if s can be segmented into a space-separated sequence of one or more dictionary words. If yes, return TRUE; else, return FALSE.
function wordBreak(s, wordDict) {
// we initialize the dp array of length s.length + 1
// dp[i] answers the question, whether or not the string up to but not including s[i] can be broken up to words
// so dp[s.length] will answer the initial question of whether or not the whole string can be broken up to words
const dp = Array(s.length + 1).fill(false);
// dp[0] is true because string up to but not inclusing s[0] is an empty string so we consider it a valid word
dp[0] = true;
// start iteration from the second character
for (let i = 1; i <= s.length; ++i) {
// inner loop starts from the first character, up to i
@optimistiks
optimistiks / palindromic-substrings.js
Created July 20, 2023 15:39
Given a string, s, return the number of palindromic substrings contained in it. A substring is a contiguous sequence of characters in a string. A palindrome is a phrase, word, or sequence that reads the same forward and backward.
function countPalindromicSubstrings(s) {
// d[i][j] answers the question: is substring [i, j) a palindrome?
const dp = Array(s.length + 1)
.fill()
.map(() => Array(s.length + 1).fill(false));
// so if the word is lever
// dp[0][5] is the answer (which means size dp size is s.length + 1 x s.length + 1)
// since every single char is a palindrome, prefill solutions to those subproblems
// in word "cat", "a" is substring [1, 2)
@optimistiks
optimistiks / longest-common-subsequence.js
Created July 27, 2023 05:56
Suppose you are given two strings. You need to find the length of the longest common subsequence between these two strings.
function longestCommonSubsequence(str1, str2) {
// prepare array m*n for top down memoization
const dp = Array(str1.length).fill().map(() => Array(str2.length).fill(null))
return rec(0, 0, str1, str2, dp)
}
function rec(i1, i2, str1, str2, dp) {
if (i1 >= str1.length || i2 >= str2.length) {
return 0
}