Skip to content

Instantly share code, notes, and snippets.

View okovalov's full-sized avatar
🏠
Working from home

Oleksandr Kovalov okovalov

🏠
Working from home
View GitHub Profile
const twoSum = (arr, num) => {
const result = []
const hash = []
for (let i in arr) {
const currentNumber = arr[i]
const expectedNumber = num - currentNumber
if (hash.indexOf(expectedNumber) !== -1) {
result.push([currentNumber, expectedNumber])
/**
* An idea how to address this 'issue'
* js> 0.1+0.2==0.3
* false
*
* The problem here is that number does not always equal to what is displayed
* js> (0.1).toPrecision(21)
* 0.100000000000000005551
* js> (0.2).toPrecision(21)
* 0.200000000000000011102
/**
* A random integer between given min and max
*/
const getRandomNumber = (min = 1, max = 10) => Math.floor(Math.random() * (max - min + 1)) + min
const min = 10
const max = 15
for (let i = 1; i <= 10; i++) {
console.log(`Random number between ${min} and ${max} = ${getRandomNumber(min, max)}`)
/**
* Fibonacci
*
* 1, 1, 2, 3, 5, 8, 13, 21, 34
*
* fibonacci = O(n^2) - exponential
* fibMemo = O(n) - linear
*/
/** O(n^2) **/
const binarySearch = (arr, key) => {
const midIdx = Math.floor(arr.length / 2)
const midElement = arr[midIdx]
if (midElement === key) return true
if (arr.length === 1) return false
if (midElement > key) {
return binarySearch(arr.splice(0, midIdx), key)
}
const sieveOfErathosphenes = num => {
const arr = [false, false]
for (let idx = 2; idx < num; idx ++) {
arr[idx] = true
}
for (let i = 2; i < Math.sqrt(num); i++) {
for (let j = 2; j * i <= num; j++) {
arr[i * j] = false
const bubbleSort = arr => {
const { length } = arr
for (let i = 0 ; i < length; i++) {
for (let j = 0; j < length - i - 1; j++) {
if (arr[j] > arr[j+1]) {
const temp = arr[j]
arr[j] = arr[j + 1]
arr[j+1] = temp
}
const mergeSort = arr => {
if (arr.length < 2) return arr
const middleIdx = Math.floor(arr.length / 2)
let left = arr.splice(0, middleIdx)
let right = arr.splice(0)
return merge(mergeSort(left), mergeSort(right))
}
/**
* n = 20
*
* test merge: 0.517ms
* test bubble: 0.204ms
*
* n = 100
*
* test merge: 3.295ms
* test bubble: 1.395ms
const maxProfit = arr => {
let bestBuyPrice = 1000000
let maxProfit = -1
for(let i = 0; i < arr.length - 1; i++) {
const currentBuyPrice = arr[i]
const nextSellPrice = arr[i+1]
if (currentBuyPrice < bestBuyPrice) bestBuyPrice = currentBuyPrice