Skip to content

Instantly share code, notes, and snippets.

View optimistiks's full-sized avatar

Max optimistiks

View GitHub Profile
@optimistiks
optimistiks / 1-reorganize-string.js
Created April 13, 2023 21:55
Given a string, rearrange it so that any two adjacent characters are not the same. If such a reorganization of the characters is possible, output any possible valid arrangement. Otherwise, return an empty string.
export function reorganizeString(inputString) {
// build a hash map where keys are characters, and values are their frequencies
const map = {};
for (let i = 0; i < inputString.length; ++i) {
const char = inputString[i];
map[char] = (map[char] ?? 0) + 1;
}
// initialize max heap by pushing character frequencies together with characters
// so heap will always contain a character with max frequency value on top
@optimistiks
optimistiks / 1-k-closest-points-to-0.js
Created April 13, 2023 22:38
Given a list of points on a plane, where the plane is a 2-D array with (x, y) coordinates, find the k closest points to the origin 0,0.
export function kClosest(points, k) {
const heap = new MaxHeap();
// put initial k points into max heap with their distances
// now we have largest distance seen so far at the top
for (let i = 0; i < k; ++i) {
const distance = getDistance(points[i]);
heap.offer([distance, points[i]]);
}
@optimistiks
optimistiks / 1-top-k-frequent-elements.js
Last active April 17, 2023 13:18
Given an array of integers arr and an integer k, return the k most frequent elements.
import MinHeap from "./min_heap.js";
export function topKFrequent(arr, k) {
// create map where we store numbers from arr as keys,
// and their frequencies in arr as values
const map = {};
// fill up frequency map
for (let i = 0; i < arr.length; ++i) {
const char = arr[i];
@optimistiks
optimistiks / 1-kth-largest-in-array.js
Created April 17, 2023 13:29
Find the kth largest element in an unsorted array.
export function findKthLargest(arr, k) {
// we are going to have min heap of size k
// it means the top of the heap is going to be the minimum element
// of all k elements in the heap
// which is exactly the kth largest element that we need
const heap = new MinHeap();
for (let i = 0; i < k; ++i) {
// initialize the heap with the first k elements from the array
heap.offer(arr[i]);
@optimistiks
optimistiks / kth-smallest-in-BST.js
Created April 17, 2023 16:25
Given the root node of a binary search tree and an integer value k, return the kth smallest value from all the nodes of the tree.
export function kthSmallestElement(root, k) {
const items = []
// traverse tree in order, creating a sorted arrat
inorder(root, (value) => items.push(value))
// grab k-1th item as a result
return items[k - 1];
}
function inorder(root, callback) {
const stack = [];
@optimistiks
optimistiks / search-in-rotated-sorted-array.js
Created April 17, 2023 20:43
Given a sorted integer array, nums, and an integer value, target, the array is rotated by some arbitrary number. Search and return the index of target in this array. If the target does not exist, return -1.
export function binarySearchRotated(nums, target) {
let low = 0;
let high = nums.length - 1;
if (nums.length === 0) {
// nothing to do if the array is empty
return -1;
}
// iteration stops once low gets larger than high (we only increase low and we only decrease high)
@optimistiks
optimistiks / find-first-bad-version.js
Created April 17, 2023 21:24
Suppose you have n versions with the IDs [1,2,...,n], and you have access to an API function that returns TRUE if the argument is the ID of a bad version. Your task is to find the first bad version, which is causing all the later ones to be bad. You have to implement a solution with the minimum number of API calls.
export function firstBadVersion(n) {
// -- DO NOT CHANGE THIS SECTION
versionApi.n = n;
// --
let start = 1;
let end = n;
let count = 0;
while (start < end) {
@optimistiks
optimistiks / 1-random-weighted-pick.js
Created April 17, 2023 21:52
You’re given an array of positive integers, w, where w[i] describes the weight of the ith index. You need to perform weighted random selection to return an index from the w array. The larger the value of w[i], the heavier the weight is. Hence, the higher the chances of its index being picked.
class RandomPickWithWeight {
constructor(w) {
// w is an array of numbers, each number is a weight of the index where it's stored
// so our task is to return a random index with respect to weights,
// so the most "heavy" index is the most probable to be returned
this.weights = w
// build an array of rolling sums
this.sums = []
for (let i = 0; i < w.length; ++i) {
const prevSum = this.sums[i - 1] || 0
@optimistiks
optimistiks / find-k-closest.js
Created April 25, 2023 14:28
Given a sorted integer array nums and two integers—k and num—return the k closest integers to num in this array. Ensure that the result is sorted in ascending order.
export function findClosestElements(nums, k, num) {
// we are going to be searching for windows
// this range indicates elements that can be first elements in a window
// hence the last element in the range is length-k
// so if a window starts from a last element in the range,
// the window does not go out of bounds
let searchRangeFirstElementIndex = 0;
let searchRangeLastElementIndex = nums.length - k;
while (searchRangeFirstElementIndex < searchRangeLastElementIndex) {
@optimistiks
optimistiks / find-single-non-duplicate.js
Created April 25, 2023 14:53
In this problem, you’re given an array of sorted integers in which all of the integers, except one, appears twice. Your task is to find the single integer that appears only once. The solution should have a time complexity of O(logn) or better and a space complexity of O(1) .
export function singleNonDuplicate(nums) {
let start = 0;
let end = nums.length - 1;
while (start < end) {
let mid = Math.floor((end - start) / 2) + start;
if (mid % 2 !== 0) {
mid -= 1;
}
if (nums[mid] !== nums[mid + 1]) {