Skip to content

Instantly share code, notes, and snippets.

View optimistiks's full-sized avatar

Max optimistiks

View GitHub Profile
@optimistiks
optimistiks / search-in-rotated-arr.js
Created May 1, 2023 21:05
You are required to find an integer t in an array arr of non-distinct integers. Arr has been processed as follows: It has been sorted in non-descending order. It has been rotated around some pivot k.
export function search(arr, t) {
// start as normal binary search
let low = 0;
let high = arr.length - 1;
while (low <= high) {
const mid = Math.floor((high - low) / 2) + low;
// if we found our target at mid, return true
if (arr[mid] === t) {
return true;
@optimistiks
optimistiks / subsets-of-ints.js
Created May 1, 2023 23:38
Given a set of integers, find all possible subsets within the set.
export function findAllSubsets(v) {
if (v.length === 0) {
return [[]];
}
const sets = [];
// total number of subsets is 2^n
const subsetsCount = 2 ** v.length;
console.log("total subsets", subsetsCount);
@optimistiks
optimistiks / 1-string-permutations.js
Created May 2, 2023 22:38
Given an input string, return all possible permutations of the string.
function swap(word, i, j) {
let swapIndex = word.split("");
let temp = swapIndex[j];
swapIndex[j] = swapIndex[i];
swapIndex[i] = temp;
return swapIndex.join("");
}
function permuteStringRec(word, pointer, result) {
// pointer is a number indication an index of a character in the string
@optimistiks
optimistiks / 1-letter-combinations-number.js
Last active May 3, 2023 21:45
Given a string having digits from 1 – 9 inclusive, return all the possible letter combinations that can be made from the numbers in the string. Return the answer in any order.
const lettersMap = {
1: [" "],
2: ["a", "b", "c"],
3: ["d", "e", "f"],
4: ["g", "h", "i"],
5: ["j", "k", "l"],
6: ["m", "n", "o"],
7: ["p", "q", "r", "s"],
8: ["t", "u", "v"],
9: ["w", "x", "y", "z"],
@optimistiks
optimistiks / 1-gen-parentheses.js
Created May 4, 2023 21:51
For a given number, n, generate all combinations of balanced parentheses.
function generateCombinationsRec(n, numOpen, numClosed, combo, result) {
// base case - length of the combination is n * 2
if (combo.length === n * 2) {
result.push(combo);
return;
}
// can we add an opening bracket to the current combination?
// yes if number of opening brackets in the combination is less than n
// so we add it, and pass it further to add more brackets, incrementing numOpen
@optimistiks
optimistiks / 1-jump-game.js
Created May 18, 2023 13:42
You’ve been provided with the nums integer array, representing the series of squares. The player starts at the first index and, following the rules of the game, tries to reach the last index. If the player can reach the last index, your function returns TRUE; otherwise, it returns FALSE.
export function jumpGame(nums) {
// take last element as our target
let target = nums.length - 1;
// start iterating from the element preceding the last, backwards
for (let i = nums.length - 2; i >= 0; --i) {
const preceding = i;
const diff = target - preceding;
// the target element is reachable from the preceding element,
// if preceding element value is greater or equal to the difference between target and preceding index
// for example, element at index 5 is reachable from element at index 4 if value at index 4 is 1 or more
@optimistiks
optimistiks / rescue-boats.js
Created May 21, 2023 20:58
You’re given an array, people, where people[i] is the weight of the ith person, and an infinite number of boats, where each boat can carry a maximum weight, limit. Each boat carries, at most, two people at the same time. This is provided that the sum of the weight of those people is under or equal to the weight limit. You need to return the mini…
// people is an array of numbers, each number represents a person's weight
// limit is the max weight of a boat
// the number of boats is unlimited
// find minimum number of boats
export function rescueBoats(people, limit) {
// sort people by weight
people.sort();
// set first pointer to point at the lightest person
let light = 0;
@optimistiks
optimistiks / gas-stations.js
Created May 21, 2023 21:06
Find the index of the gas station in the integer array gas such that if we start from that index we may return to the same index by traversing through all the elements, collecting gas[i] and consuming cost[i].
// gas is an array of numbers, where each number represents the amount of gas we can put in our car fuel tank on ith gas station.
// cost is how much gas we need to spend to move from gas station i to gas station i+1.
// we need to find an index of the gas station from which we can start our journey and visit every gas station.
export function gasStationJourney(gas, cost) {
// first, calculate total amount of gas in all gas stations
const totalGas = gas.reduce((acc, amount) => acc + amount, 0);
// second, calculate the gas cost of the whole journey
const totalCost = cost.reduce((acc, amount) => acc + amount, 0);
if (totalCost > totalGas) {
@optimistiks
optimistiks / two-city-scheduling.js
Created May 21, 2023 22:31
Return the minimum cost to fly every person to a city such that exactly n people arrive in each city.
export function twoCityScheduling(costs) {
// create an array of cost differences and sort it ascending
const diffs = costs.map(([costA, costB]) => costA - costB);
diffs.sort((a, b) => a - b);
// get a sum of all costs to city A (like we sent all people to city A)
let sumA = costs.reduce((sum, [costA]) => sum + costA, 0);
// since we are actually sending the second half of people (by diffs) to city B
// subtract their differences (think refunds) from the sumA
@optimistiks
optimistiks / min-refueling-stops.js
Created May 22, 2023 23:02
You need to find the minimum number of refueling stops that a car needs to make to cover a distance (target). Stations is an array of tuples [distance, fuel]. 1 distance = 1 fuel.
export function minRefuelStops(target, startFuel, stations) {
if (startFuel >= target) {
// if we have enough fuel to cover the target
return 0;
}
// we're going to store fuels of reachable stations in a max heap
const heap = new MaxHeap();
// max distance that we can cover in the current moment (equals to amount of fuel since 1 mile = 1 fuel)
let maxDistance = startFuel;