├── 01-04 ├── NumberofCharsEscaped.js ├── RacingCar.js └── signalFilter.js ├── 01-25 ├── BucketFill.js ├── cuttingMetalSurplus.js └── slowestKeyPress.js ├── 02-01 ├── BackspaceStringCompare.js ├── competitiveGaming.js ├── mergeIntervals.js └── reachEndInTime.js ├── 02-08 ├── firstUniqueChar.js ├── scatterPalindrome.js └── throttlingGateway.js ├── 02-15 ├── BinaryNumberInLinkedList.js ├── monsoonUmbrella.js └── wholeMinuteDilemma.js ├── 02-22 ├── autoScalePolicy.js ├── countingPairs.js ├── funWithAnagrams.js └── maxOcurringChar.js ├── 03-08 ├── customSortedArray.js ├── gapsInTraffic.js ├── metroLandFestival.js └── rumbleInTokyo.js ├── 03-15 ├── canYouMakeAPalindrome.js ├── chooseAFlask.js └── minimumMoves.js ├── 03-22 ├── deviceNameSystem.js ├── mergeBetween.js └── teamFormation.js ├── 03-29 ├── degreeOfArray.js ├── intelligentSubstring.js └── longestBitonicSubArray.js ├── 04-19 ├── firstUniqueChar.js ├── numberOfMoves.js └── wholeMinuteDelimma.js ├── 04-26 ├── efficientJanitor.js ├── reachTheEndInTime.js └── simpleMaxDifference.js ├── 06-07 ├── bucketFill.js ├── numberOfMoves.js ├── scatterPalindrome.js └── sellingProducts.js ├── 06-21 ├── groupAnagrams.js ├── mergeInterval.js └── slowestKeyPress.js ├── 06-28 ├── EfficientJanitor.js ├── FirstUniqueChar.js ├── pickingTickets.js └── wholeMinuteDilemma.js ├── 08-24 ├── minimumSum.js └── pileofboxes.js ├── 08-31 ├── chooseAFlask.js ├── howmanyWords.js └── longestIncreasingSubsequence.js ├── 09-08 ├── bucketFill.js ├── perfectSubstring.js └── sellingProducts.js ├── 09-14 ├── competitiveGaming.js ├── numberOfMoves.js └── simpleMaxDifference.js ├── 09-21 ├── almostSameStrings.js ├── findtheFactor.js ├── scatterPalindrome.js └── throttlingGateway.js ├── 09-28 ├── Price_check.js ├── ProfitTargets.js └── ReachTheEndInTime.js ├── 10-05 ├── AnagramDifference.js ├── CountingPairs.js ├── ShoppingCartBilling.js └── maximumRatingSum.js ├── 10-12 ├── ArrayGame.js ├── EvenSubarray.js └── WebsitePagination.js ├── 10-19 ├── efficientCost.js ├── efficientStudy.js └── gameSegments.js ├── 10-26 ├── efficentJanito.js ├── minimumMoves.js └── parkingTickets.js ├── 11-16 ├── TwinStrings.js ├── busStrand.js └── findTheSequenceSum.js ├── 11-2 ├── autoscalePolicy.js └── teamFormation.js ├── 11-30 ├── minimumSwaps.js ├── rumbleInTokyo.js └── wholeMinuteDilemma.js ├── 11-9 ├── counterfeitCurrency.js ├── liftingWeight.js └── wordCompression.js ├── 12-14 ├── blah.js ├── gameWinner.js ├── groupingDigits.js └── profitTargets.js ├── 12-7 ├── arrayReduction.js ├── co-prime.js ├── countingClosedPaths.js └── getUmbrellas.js └── 4-12 ├── countBinarySubstrings.js ├── cuttingMetalSurplus.js ├── jumptheflag.js └── rollTheString.js /01-04/NumberofCharsEscaped.js: -------------------------------------------------------------------------------- 1 | function numberOfCharactersEscaped(expression) { 2 | 3 | let alpha = 'abcdefghijklmnopqrstuvwxyz' 4 | let checkIndices = [] 5 | let bool = false 6 | let result = 0 7 | 8 | for (let i = 0; i < expression.length; i++) { 9 | if (expression[i] !== '#' && bool === true) { 10 | checkIndices.push(i) 11 | } else if (expression[i] === '#' && bool === false) { 12 | bool = true 13 | } else if (expression[i] === '#' && bool === true) { 14 | bool = false 15 | } 16 | } 17 | debugger 18 | for (let i = 0; i < expression.length; i++) { 19 | if (checkIndices.includes(i)) { 20 | if (alpha.includes(expression[i]) && expression[i - 1] === '!') result++ 21 | } 22 | } 23 | return result 24 | 25 | } -------------------------------------------------------------------------------- /01-04/RacingCar.js: -------------------------------------------------------------------------------- 1 | function minimumMovement(obstacleLanes) { 2 | // 2,1,3,2 3 | // [ 4 | // [2,inf,3] 5 | // [2, 2 ,inf] 6 | // [inf, 2 , 1] 7 | // [1 ,inf, 1] 8 | // [1, 0, 1] 9 | // ] 10 | 11 | 12 | 13 | 14 | // Write your code here 15 | //creating grid of car rows 16 | let carRows = new Array(obstacleLanes.length) 17 | .fill('') 18 | .map(() => 19 | new Array(3).fill('') 20 | ) 21 | 22 | //looping over nested arrays to add obstacles 23 | for (let i = 0; i < carRows.length; i++) { 24 | carRows[i][obstacleLanes[i] - 1] = Infinity; 25 | } 26 | 27 | //start of moves 28 | carRows.unshift([1, 0, 1]); 29 | 30 | //checking each available position and assigning it its respective number of moves 31 | for (let i = 1; i < carRows.length; i++) { 32 | for (let j = 0; j < 3; j++) { 33 | let nextPossibleRow = carRows[i][j] 34 | let prevRowPos = carRows[i - 1][j] 35 | if (nextPossibleRow === '' && prevRowPos === Infinity) { 36 | carRows[i][j] = Math.min(...carRows[i - 1]) + 1 37 | } else if (nextPossibleRow === '' && prevRowPos !== Infinity) { 38 | carRows[i][j] = carRows[i - 1][j] 39 | } 40 | } 41 | } 42 | return Math.min(...carRows[carRows.length - 1]) 43 | } -------------------------------------------------------------------------------- /01-04/signalFilter.js: -------------------------------------------------------------------------------- 1 | function countSignals(frequencies, filterRanges) { 2 | // Write your code here 3 | let low = -Infinity 4 | let high = Infinity 5 | for (let filters of filterRanges) { 6 | let val1 = filters[0] 7 | let val2 = filters[1] 8 | if (val1 > low) low = val1 9 | if (val2 < high) high = val2 10 | } 11 | let count = 0 12 | for (let freq of frequencies) { 13 | if (freq >= low && freq <= high) count++ 14 | } 15 | return count 16 | } -------------------------------------------------------------------------------- /01-25/BucketFill.js: -------------------------------------------------------------------------------- 1 | function strokesRequired(picture) { 2 | let matrix = picture.map(ele => ele.split("")); 3 | let visited = matrix.map(row => row.map(value => false)); 4 | 5 | let count = 0; 6 | for (let row = 0; row < matrix.length; row++) { 7 | for (let col = 0; col < matrix[0].length; col++) { 8 | if (!visited[row][col]) { 9 | let letter = matrix[row][col]; 10 | color(row, col, letter, visited, matrix); 11 | count++; 12 | } 13 | } 14 | } 15 | 16 | return count; 17 | } 18 | 19 | function color(row, col, letter, visited, matrix) { 20 | let squares = [[row, col]]; 21 | 22 | while (squares.length) { 23 | let node = squares.shift(); 24 | let x = node[0]; 25 | let y = node[1]; 26 | visited[x][y] = true; 27 | let neighbors = getNeighbors(x, y, letter, visited, matrix); 28 | squares = squares.concat(neighbors); 29 | } 30 | } 31 | 32 | function getNeighbors(row, col, letter, visited, matrix) { 33 | let dirs = [[1, 0], [0, 1], [-1, 0], [0, -1]]; 34 | let neighbors = []; 35 | 36 | for (let i = 0; i < dirs.length; i++) { 37 | let newX = row + dirs[i][0]; 38 | let newY = col + dirs[i][1]; 39 | if (newX >= 0 && newX < matrix.length && newY >= 0 && newY < matrix[0].length) { 40 | if (!visited[newX][newY]) { 41 | if (matrix[newX][newY] === letter) { 42 | neighbors.push([newX, newY]); 43 | visited[newX][newY] = true; 44 | } 45 | } 46 | 47 | } 48 | } 49 | 50 | return neighbors; 51 | 52 | 53 | } 54 | -------------------------------------------------------------------------------- /01-25/cuttingMetalSurplus.js: -------------------------------------------------------------------------------- 1 | function maxProfit(costPerCut, salePrice, lengths) { 2 | // Write your code here 3 | let maxProfit = 0 4 | let max = Math.max(...lengths) 5 | let test; 6 | for (let i = 1; i <= max; i++) { 7 | test = helper(i, costPerCut, salePrice, lengths) 8 | maxProfit = Math.max(maxProfit, test) 9 | } 10 | return maxProfit 11 | } 12 | 13 | 14 | function helper(currLength, costPerCut, salePrice, lengths) { 15 | let totalUniformRods = 0; 16 | let totalCuts = 0 17 | for (let i = 0; i < lengths.length; i++) { //[20, 59, 110] - currLength =2 18 | let currRod = lengths[i]; //20 19 | if (currLength > currRod) continue 20 | let tempCut = 0 21 | let tempTotalUniformRods = 0 22 | 23 | if (currRod % currLength === 0) { 24 | tempCut = Math.floor(currRod / currLength) - 1 25 | 26 | } else { 27 | tempCut = Math.floor(currRod / currLength) 28 | } 29 | tempTotalUniformRods = Math.floor(currRod / currLength) 30 | if (tempTotalUniformRods * currLength * salePrice - tempCut * costPerCut > 0) { 31 | totalCuts += tempCut 32 | totalUniformRods += tempTotalUniformRods 33 | 34 | } 35 | } 36 | return totalUniformRods * currLength * salePrice - totalCuts * costPerCut 37 | } 38 | -------------------------------------------------------------------------------- /01-25/slowestKeyPress.js: -------------------------------------------------------------------------------- 1 | function slowestKey(keyTimes) { 2 | // Write your code here 3 | if (keyTimes === null || keyTimes.length === 0) return null; 4 | 5 | let maxTime = -Infinity; 6 | let alphabet = "abcdefghijklmnopqrstuvwxyz"; 7 | let key; 8 | let prevTime = 0; 9 | 10 | for (let i = 0; i < keyTimes.length; i++) { 11 | if (keyTimes[i][1] - prevTime > maxTime) { 12 | maxTime = keyTimes[i][1] - prevTime; 13 | key = alphabet[keyTimes[i][0]]; 14 | } 15 | prevTime = keyTimes[i][1]; 16 | } 17 | return key; 18 | } -------------------------------------------------------------------------------- /02-01/BackspaceStringCompare.js: -------------------------------------------------------------------------------- 1 | function compareStrings(s1, s2) { 2 | // Write your code here 3 | let stack1 = [] 4 | let stack2 = [] 5 | for (let i = 0; i < s1.length; i++) { 6 | if (s1[i] === '#') { 7 | stack1.pop(); 8 | } else { 9 | stack1.push(s1[i]) 10 | } 11 | } 12 | for (let i = 0; i < s2.length; i++) { 13 | if (s2[i] === '#') { 14 | stack2.pop(); 15 | } else { 16 | stack2.push(s2[i]) 17 | } 18 | } 19 | 20 | return stack1.join('') === stack2.join('') ? 1 : 0 21 | 22 | } -------------------------------------------------------------------------------- /02-01/competitiveGaming.js: -------------------------------------------------------------------------------- 1 | function numPlayers(k, scores) { 2 | //[100, 100, 50, 25] k = 3 3 | let sortedScores = scores.sort((a, b) => b - a); 4 | let ranks = new Array(sortedScores.length).fill(0); //[1,1,0,0] 5 | ranks[0] = 1; 6 | 7 | let pos = 2; //4 8 | for (let i = 1; i < sortedScores.length; i++) { 9 | if (sortedScores[i] === sortedScores[i - 1]) { 10 | ranks[i] = ranks[i - 1]; 11 | } else { 12 | ranks[i] = pos; 13 | } 14 | pos++; 15 | } 16 | 17 | let count = 0; 18 | for (let i = 0; i < ranks.length; i++) { 19 | if (ranks[i] <= k) { 20 | if (sortedScores[i] > 0) count++; 21 | } 22 | } 23 | 24 | return count; 25 | 26 | } -------------------------------------------------------------------------------- /02-01/mergeIntervals.js: -------------------------------------------------------------------------------- 1 | function getMergedIntervals(intervals) { 2 | // Write your code here 3 | if (intervals.length === 0) return []; 4 | 5 | intervals.sort((a, b) => a[0] - b[0]); 6 | let result = [intervals[0]]; 7 | 8 | for (let i = 1; i < intervals.length; i++) { 9 | let prev = result[result.length - 1]; 10 | let curr = intervals[i]; 11 | if (prev[1] >= curr[0]) { 12 | prev[0] = Math.min(prev[0], curr[0]); 13 | prev[1] = Math.max(prev[1], curr[1]); 14 | } else { 15 | result.push(curr); 16 | } 17 | } 18 | 19 | return result; 20 | 21 | } 22 | 23 | -------------------------------------------------------------------------------- /02-01/reachEndInTime.js: -------------------------------------------------------------------------------- 1 | function reachTheEnd(grid, maxTime) { 2 | const visited = new Set().add('0-0') 3 | const dirs = [[1, 0], [-1, 0], [0, -1], [0, 1]] 4 | let queue = [[0, 0, 0]] 5 | let minTime = Infinity 6 | let gridLen = grid.length 7 | let gridWid = grid[0].length 8 | 9 | while (queue.length) { 10 | const pathNodes = [] 11 | for (let i = 0; i < queue.length; i++) { 12 | const [row, col, time] = queue[i] 13 | 14 | if (row === gridLen - 1 && col === gridWid - 1) { 15 | minTime = Math.min(minTime, time) 16 | continue 17 | } 18 | 19 | for (let i = 0; i < dirs.length; i++) { 20 | let newRow = row + dirs[i][0]; 21 | let newCol = col + dirs[i][1]; 22 | if (validMove(newRow, newCol, gridLen, gridWid, visited, grid)) { 23 | pathNodes.push([newRow, newCol, time + 1]) 24 | } 25 | } 26 | } 27 | queue = pathNodes 28 | } 29 | 30 | return minTime <= maxTime ? 'Yes' : 'No' 31 | } 32 | 33 | function validMove(row, col, gridLen, gridWid, visited, grid) { 34 | if (visited.has(`${row}-${col}`)) return false 35 | else visited.add(`${row}-${col}`) 36 | 37 | if (row < gridLen && row >= 0 && col < gridWid && col >= 0) { 38 | if (grid[row][col] !== '#') { 39 | return true 40 | } else { 41 | return false 42 | } 43 | } 44 | 45 | 46 | } -------------------------------------------------------------------------------- /02-08/firstUniqueChar.js: -------------------------------------------------------------------------------- 1 | function getUniqueCharacter(s) { 2 | // Write your code here 3 | 4 | let hash = {} 5 | s = s.split('') 6 | for (const char of s) { 7 | if (!hash[char]) hash[char] = 0 8 | hash[char] += 1 9 | } 10 | let unique = [] 11 | Object.keys(hash).forEach(key => { 12 | if (hash[key] === 1) unique.push(key) 13 | }) 14 | for (let i = 0; i < s.length; i++) { 15 | if (unique.includes(s[i])) return i + 1 16 | } 17 | return -1 18 | } -------------------------------------------------------------------------------- /02-08/scatterPalindrome.js: -------------------------------------------------------------------------------- 1 | // ['aabb', 'tacocat'] => a, aa, aab, aabb, a, abb, b, bb, b => 9 2 | 3 | function scatterPalindrome(string) { 4 | let result = [] 5 | for (let i = 0; i < string.length; i++) { 6 | let str = string[i]; 7 | let count = 0 // j 8 | for (let j = 0; j < str.length; j++) { // aabb 9 | let set = new Set(); //{} 10 | for (let k = j; k < str.length; k++) { 11 | if (set.has(str[k])) { 12 | set.delete(str[k]) 13 | } else { 14 | set.add(str[k]) 15 | } 16 | if (set.size < 2) count++ 17 | } 18 | 19 | } 20 | result.push(count) 21 | } 22 | return result 23 | } -------------------------------------------------------------------------------- /02-08/throttlingGateway.js: -------------------------------------------------------------------------------- 1 | function droppedRequests(requestTime) { 2 | // Write your code here 3 | // [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, 11, 11, 11, 11 ] 4 | const uniqueSetoftime = new Set(requestTime) //{1,2,3,4,5,6,11} 5 | const freqs = {} 6 | let dropRequests = 0 7 | 8 | for (let i = 0; i < requestTime.length; i++) { 9 | const reqTime = requestTime[i] 10 | if (!freqs[reqTime]) { 11 | freqs[reqTime] = { ones: 0, tens: 0, mins: 0 } 12 | } 13 | freqs[reqTime].ones++ 14 | for (let j = 0; j < 60; j++) { 15 | const newRT = reqTime + j 16 | if (!uniqueSetoftime.has(newRT)) continue 17 | if (!freqs[newRT]) { 18 | freqs[newRT] = { ones: 0, tens: 0, mins: 0 } 19 | } 20 | if (j < 10) freqs[newRT].tens++ 21 | freqs[newRT].mins++ 22 | } 23 | if (freqs[reqTime].ones > 3 || freqs[reqTime].tens > 20 || freqs[reqTime].mins > 60) dropRequests++ 24 | } 25 | return dropRequests 26 | 27 | } -------------------------------------------------------------------------------- /02-15/BinaryNumberInLinkedList.js: -------------------------------------------------------------------------------- 1 | function getNumber(binary) { 2 | let total = 0n; 3 | while (binary !== null) { 4 | total *= 2n; 5 | total += BigInt(binary.data); 6 | binary = binary.next; 7 | } 8 | return total; 9 | } -------------------------------------------------------------------------------- /02-15/monsoonUmbrella.js: -------------------------------------------------------------------------------- 1 | function getUmbrellas(requirement, sizes) { 2 | // Write your code here 3 | //[2,4] 4 | //0. 1. 2. 3. 4. 5 | //[0,inf,1, inf, 1] 6 | const coveredDPA = new Array(requirement + 1).fill(Infinity); 7 | coveredDPA[0] = 0; 8 | for (let size of sizes) { 9 | for (let i = 0; i < coveredDPA.length; i++) { 10 | if (size <= i) { 11 | coveredDPA[i] = Math.min(coveredDPA[i], coveredDPA[i - size] + 1) 12 | } 13 | } 14 | } 15 | if (coveredDPA[requirement] !== Infinity) { 16 | return coveredDPA[requirement] 17 | } else { 18 | return -1 19 | } 20 | } -------------------------------------------------------------------------------- /02-15/wholeMinuteDilemma.js: -------------------------------------------------------------------------------- 1 | function playlist(songs) { 2 | // Write your code here 3 | //[10, 50, 90, 30, 30] 4 | songs = songs.map(time => time % 60) 5 | const counter = {} //{10:1,30:2} 6 | let pairs = 0 //4 7 | songs.forEach(song => { //[10,50,30,30,30] 8 | const diff = (60 - song) % 60 9 | if (counter[diff]) pairs += counter[diff] 10 | if (!counter[song]) { 11 | counter[song] = 0 12 | } 13 | counter[song]++ 14 | }) 15 | return pairs 16 | 17 | } 18 | -------------------------------------------------------------------------------- /02-22/autoScalePolicy.js: -------------------------------------------------------------------------------- 1 | function finalInstances(instances, averageUtil) { 2 | const halfMaxInstances = 2 * (10 ** 8) 3 | let i = 0 4 | 5 | while (i < averageUtil.length) { 6 | const u = averageUtil[i] 7 | 8 | if (u < 25 && instances > 1) { 9 | instances = Math.ceil(instances / 2) 10 | i += 10 11 | } else if (u > 60 && (instances * 2) < halfMaxInstances) { 12 | instances *= 2 13 | i += 10 14 | } 15 | i++ 16 | } 17 | 18 | return instances 19 | } -------------------------------------------------------------------------------- /02-22/countingPairs.js: -------------------------------------------------------------------------------- 1 | function countPairs(numbers, k) { 2 | 3 | // k=1 4 | 5 | 6 | // set to save the values of a where a = b - k 7 | // k = b-a 8 | const aValues = new Set() 9 | for (let i = 0; i < numbers.length; i++) { 10 | let a = numbers[i] - k 11 | if (aValues.has(a)) { 12 | continue 13 | } else { 14 | aValues.add(a) 15 | } 16 | } 17 | // set ={0} 18 | let count = 0 //2 19 | for (let i = 0; i < numbers.length; i++) { 20 | if (aValues.has(numbers[i])) { 21 | count++ 22 | aValues.delete(numbers[i]) 23 | } 24 | } 25 | return count 26 | } -------------------------------------------------------------------------------- /02-22/funWithAnagrams.js: -------------------------------------------------------------------------------- 1 | 2 | function funWithAnagrams(text) { 3 | O(n * mlog(m)) //n is the length of text.and m is the length of each word 4 | // Write your code here 5 | // text = text.sort() 6 | let hash = {} 7 | let stack = [] 8 | for (let i = 0; i < text.length; i++) { 9 | let word = text[i] 10 | let sorted = text[i].split('').sort().join('') 11 | if (!hash[sorted]) { 12 | hash[sorted] = true 13 | stack.push(word) 14 | } 15 | } 16 | return stack.sort() 17 | 18 | } -------------------------------------------------------------------------------- /02-22/maxOcurringChar.js: -------------------------------------------------------------------------------- 1 | function maximumOccurringCharacter(text) { 2 | // Write your code here 3 | let max = 0 4 | let letter; 5 | text = text.split('') 6 | let hash = {} 7 | for (const char of text) { 8 | if (!hash[char]) hash[char] = 0 9 | hash[char] += 1 10 | 11 | } 12 | 13 | Object.keys(hash).forEach(key => { 14 | if (hash[key] > max) { 15 | max = hash[key] 16 | letter = key 17 | } 18 | }) 19 | return letter 20 | 21 | } -------------------------------------------------------------------------------- /03-08/customSortedArray.js: -------------------------------------------------------------------------------- 1 | function moves(arr) { 2 | // Write your code here 3 | let count = 0 4 | let evenPointer = arr.length - 1 5 | let oddPointer = 0 6 | while (oddPointer < evenPointer) { 7 | while (arr[oddPointer] % 2 === 0) oddPointer++ 8 | while (arr[evenPointer] % 2 !== 0) evenPointer-- 9 | if (oddPointer < evenPointer) { 10 | [arr[oddPointer], arr[evenPointer]] = [arr[evenPointer], arr[oddPointer]] 11 | count++ 12 | } 13 | oddPointer++ 14 | evenPointer-- 15 | 16 | } 17 | return count 18 | 19 | } -------------------------------------------------------------------------------- /03-08/gapsInTraffic.js: -------------------------------------------------------------------------------- 1 | function widestGap(n, start, finish) { 2 | let lanes = [] 3 | let i = 0; 4 | while (i < start.length) { 5 | lanes.push([start[i], finish[i]]) 6 | i++ 7 | } 8 | lanes = lanes.sort((a, b) => { 9 | if (a[0] !== b[0]) { 10 | return a[0] - b[0] 11 | } else { 12 | return a[1] - b[1] 13 | } 14 | }) 15 | //[[1,2],[2,2],[4,6],[8,8]] 16 | 17 | lanes.push([n + 1, n + 1]) 18 | let maxFinish = 0 //2 19 | let maxGap = 0 //0 20 | let j = 0; 21 | while (j < lanes.length) { 22 | let strt = lanes[j][0] //5 23 | let end = lanes[j][1] //6 24 | if (maxFinish < strt) maxGap = Math.max(maxGap, strt - maxFinish - 1) 25 | maxFinish = Math.max(maxFinish, end) 26 | j++ 27 | } 28 | return maxGap 29 | } 30 | -------------------------------------------------------------------------------- /03-08/metroLandFestival.js: -------------------------------------------------------------------------------- 1 | function minimizeCost(numPeople, x, y) { 2 | // Write your code here 3 | let xCord = [] //[1,1,3,3,3,3] 4 | let yCord = [] //[1,1,3,3,3,3] 5 | let answer = 0; 6 | for (let i = 0; i < numPeople.length; i++) { 7 | let peopleCount = numPeople[i] //1 8 | while (peopleCount) { 9 | xCord.push(x[i]) 10 | yCord.push(y[i]) 11 | peopleCount-- 12 | } 13 | } 14 | 15 | xCord = xCord.sort((a, b) => a - b) 16 | yCord = yCord.sort((a, b) => a - b) 17 | 18 | let len = xCord.length 19 | let mid = Math.floor(len / 2) 20 | 21 | let medianX = xCord[mid] 22 | let medianY = yCord[mid] 23 | 24 | 25 | for (let i = 0; i < numPeople.length; i++) { 26 | answer += numPeople[i] * cost(medianX, medianY, x[i], y[i]) 27 | } 28 | return answer 29 | } 30 | 31 | 32 | function cost(medianX, medianY, a, b) { 33 | return (Math.abs(medianX - a) + Math.abs(medianY - b)) 34 | } -------------------------------------------------------------------------------- /03-08/rumbleInTokyo.js: -------------------------------------------------------------------------------- 1 | function getMinimumBlows(height) { 2 | if (height.length < 3) return 1 3 | 4 | const minHit = new Array(height.length) 5 | 6 | let hits = 0 //1 7 | let currHeight = 0 //2 8 | for (let i = 0; i < height.length; i++) { 9 | let building = height[i] //3 10 | if (!hits || building < currHeight) hits++ 11 | currHeight = building 12 | minHit[i] = hits 13 | } 14 | 15 | hits = 0 //3 16 | currHeight = 0 17 | //[6,5,4,3,4,5,4,5,6] 18 | for (let i = height.length - 1; i >= 0; i--) { 19 | let building = height[i] //3 20 | if (!hits || building < currHeight) hits++ 21 | currHeight = building //4 22 | minHit[i] += hits 23 | } 24 | 25 | return Math.min(...minHit) 26 | } 27 | -------------------------------------------------------------------------------- /03-15/canYouMakeAPalindrome.js: -------------------------------------------------------------------------------- 1 | function palindromeChecker(s, startIndex, endIndex, subs) { 2 | // s = cdecd 3 | // startIndex =[0, 0, 0, 0] 4 | // endIndex = [0, 1, 2, 3] 5 | // subs = [0, 1, 1, 0] 6 | 7 | 8 | // let startEnd = [] 9 | let i = 0; 10 | let resultStr = '' 11 | while(i < startIndex.length){ 12 | startEnd.push([startIndex[i],endIndex[i]]) 13 | i++ 14 | } 15 | // debugger 16 | 17 | let j = 0; 18 | while (j < startIndex.length) { 19 | let currStart = startEnd[j][0] 20 | let currEnd = startEnd[j][1] + 1 21 | let currString = s.slice(currStart, currEnd) 22 | let currChangeCount = subs[j] 23 | let palindromeCheck = isPalindrome(currString) 24 | 25 | if (currString.length < 4 && currChangeCount > 0) { 26 | resultStr += '1' 27 | } else { 28 | while (currChangeCount > 0) { 29 | if (palindromeCheck === true) { 30 | resultStr += '1' 31 | break 32 | } else { 33 | palindromeCheck = palindromeCheck - 2 < 2 ? true : palindromeCheck - 2 34 | currChangeCount-- 35 | } 36 | } 37 | if (palindromeCheck === true && resultStr.length - 1 !== j) resultStr += '1' 38 | if (resultStr.length - 1 !== j) resultStr += '0' 39 | } 40 | j++ 41 | } 42 | 43 | return resultStr 44 | 45 | 46 | } 47 | 48 | 49 | function isPalindrome(str) { 50 | str = str.split('') 51 | let set = new Set() 52 | for (let char of str) { 53 | if (set.has(char)) { 54 | set.delete(char) 55 | } else { 56 | set.add(char) 57 | } 58 | } 59 | if (set.size < 2) return true 60 | return set.size 61 | } 62 | 63 | 64 | 65 | // from collections import Counter 66 | // ​ 67 | // # Total time = O(S + Q) where S is number of chars in S and Q is number of queries 68 | 69 | // def palindromeChecker(s, startIndex, endIndex, subs): 70 | 71 | // def palindromable(c, numSubs): 72 | // ​ 73 | // # This method recives a Counter(hash where key = char, value = number of times it appears) and the number of 74 | // # allowed substitutions 75 | // # It returns True / False depending on whether a palindrome can be made w / the counter w / the number of subs 76 | // # If the total number of characters is odd, we can have one key with odd value 77 | // # If even, zero. 78 | // # Each substitution allows us to nuke two odds 79 | 80 | // numOdd = 0 81 | // numEven = 0 82 | // total = 0 83 | // for char in c: 84 | // if c[char] % 2 == 0: 85 | // numEven += 1 86 | // else: 87 | // numOdd += 1 88 | // total += c[char] 89 | // if total % 2 == 0: 90 | // return 2 * numSubs >= numOdd 91 | // else: 92 | // return 2 * numSubs >= numOdd - 1 93 | 94 | // # freqs[k] = a Counter of all chars appearing in the string up to character k in s. 95 | // # For each character in s, we update a running frequency counter. 96 | // # Then we make a copy of the counter(O(1) since there are only 26 characters) and save it in freqs[] 97 | 98 | // freqs = [] 99 | // baseCounter = Counter("") 100 | // for k in range(len(s)): 101 | // baseCounter.update(s[k]) 102 | // freqs.append(baseCounter.copy()) 103 | // ​ 104 | // # Observe that to get the frequency of chars appearing in s[x...y], 105 | // # we can just subtract the numbers for s[..x] from s[...y] => freqs[y] - freqs[x] 106 | // # This can be done in O(1) time.The "-" operation defined in the Counter class abstracts away the work 107 | // # of subtracting the numbers of each character type. 108 | 109 | // def getSubfreq(x, y): 110 | // if x == 0: return freqs[y] 111 | // else: return freqs[y] - freqs[x - 1] 112 | // ​ 113 | // # For each query, as we can get the subarray frequency in O(1) time 114 | // # and check it for palindromicity w / acceptable subs in O(1) time 115 | // # This loop is O(Q) where Q is the number of queries. 116 | 117 | // answer = [] 118 | // for k in range(len(startIndex)): 119 | // x = startIndex[k] 120 | // y = endIndex[k] 121 | // if palindromable(getSubfreq(x, y), subs[k]): 122 | // answer.append("1") 123 | // else: 124 | // answer.append("0") 125 | 126 | // return "".join(answer) 127 | 128 | 129 | // print(palindromeChecker("bcba", [1, 2, 1], [3, 3, 1], [2, 0, 0]), "101") -------------------------------------------------------------------------------- /03-15/chooseAFlask.js: -------------------------------------------------------------------------------- 1 | function chooseFlask(requirements, flaskTypes, markings) { 2 | requirements = requirements.sort((a, b) => a - b) 3 | let minWaste = [Infinity, -1] 4 | let i = 0 5 | let j = 0 6 | while (i < flaskTypes) { 7 | let currWasteSum = 0 8 | let reqNum = 0 9 | let currFlaskNum = i 10 | while (reqNum < requirements.length && j < markings.length && markings[j][0] === currFlaskNum) { 11 | if (requirements[reqNum] > markings[j][1]) { 12 | j++ 13 | } else { 14 | currWasteSum += markings[j][1] - requirements[reqNum] 15 | reqNum++ 16 | } 17 | } 18 | i++ 19 | while (j < markings.length && markings[j][0] === currFlaskNum) { j++ } 20 | if (reqNum !== requirements.length) continue 21 | 22 | if (currWasteSum < minWaste[0]) { 23 | minWaste[0] = currWasteSum 24 | minWaste[1] = currFlaskNum 25 | } 26 | } 27 | 28 | return minWaste[1] 29 | } -------------------------------------------------------------------------------- /03-15/minimumMoves.js: -------------------------------------------------------------------------------- 1 | function minimumMoves(arr1, arr2) { 2 | // Write your code here 3 | let count = 0; 4 | for (let i = 0; i < arr1.length; i++) { 5 | let int1 = arr1[i]; 6 | let int2 = arr2[i]; 7 | count += helper(int1, int2) 8 | } 9 | return count; 10 | } 11 | 12 | // arr1 = [123, 543] 13 | // arr2 = [321, 279] 14 | 15 | function helper(int1, int2) { //1 - 3 16 | let num = 0; 17 | while (int1 !== 0) { 18 | num += Math.abs(int1 % 10 - int2 % 10); 19 | int1 = Math.floor(int1 / 10); 20 | int2 = Math.floor(int2 / 10); 21 | } 22 | return num; 23 | } 24 | -------------------------------------------------------------------------------- /03-22/deviceNameSystem.js: -------------------------------------------------------------------------------- 1 | function deviceNamesSystem(devicenames) { 2 | const deviceNum = {}; //{switch:3, tv:2} 3 | 4 | for (let i = 0; i < devicenames.length; i++) { 5 | const devName = devicenames[i]; 6 | 7 | if (!deviceNum[devName]) { 8 | deviceNum[devName] = 1; 9 | } else { 10 | devicenames[i] += deviceNum[devName]; 11 | deviceNum[devName] += 1; 12 | } 13 | } 14 | 15 | return devicenames; 16 | } 17 | -------------------------------------------------------------------------------- /03-22/mergeBetween.js: -------------------------------------------------------------------------------- 1 | function mergeInBetween(list1, list2, a, b) { 2 | // Write your code here 3 | let pointerA = list1 4 | let endL2 = list2 // 9 node 5 | let prev = null 6 | while (endL2.next) endL2 = endL2.next 7 | while (a > 1) { 8 | prev = pointerA //prev = node 1 9 | pointerA = pointerA.next // pointerA = node2 10 | a -= 1 //a = 1 11 | } 12 | let pointerB = list1 13 | while (b > 0) { 14 | pointerB = pointerB.next // pointerB = node4 15 | b -= 1 //b=0 16 | } 17 | endL2.next = pointerB 18 | 19 | if (prev) { 20 | prev.next = list2 21 | return list1 22 | } 23 | return list2 24 | 25 | 26 | 27 | } -------------------------------------------------------------------------------- /03-22/teamFormation.js: -------------------------------------------------------------------------------- 1 | function countTeams(skills, minPlayers, minLevel, maxLevel) { 2 | let validPlayers = skills.filter(player => player >= minLevel && player <= maxLevel); 3 | let numValid = validPlayers.length; 4 | let teamSize = validPlayers.length; 5 | let totalTeams = 0; 6 | while (teamSize >= minPlayers) { 7 | // nCr n = how many combinations from n can be made in size r 8 | totalTeams += (factorial(numValid)) / ((factorial(teamSize) * factorial(numValid - teamSize))); 9 | teamSize--; 10 | } 11 | 12 | function factorial(n) { 13 | if (n === 0) return 1; 14 | return n * factorial(n - 1); 15 | } 16 | 17 | return totalTeams; 18 | } 19 | -------------------------------------------------------------------------------- /03-29/degreeOfArray.js: -------------------------------------------------------------------------------- 1 | function degreeOfArray(arr) { 2 | // Write your code here 3 | let countHash = {} //{1:2, 2:2, 3:1} 4 | let firstOccurance = {} // {1:0,2:1, 3:3} 5 | let lastOccurance = {}//{1:4,2:2,3:3} 6 | let max = 0 7 | debugger 8 | for (let i = 0; i < arr.length; i++) { 9 | let num = arr[i] 10 | if (!countHash[num]) countHash[num] = 0 11 | countHash[num] += 1 12 | max = Math.max(max, countHash[num]) 13 | if (!(num in firstOccurance)) firstOccurance[num] = i 14 | lastOccurance[num] = i 15 | } 16 | 17 | let minSubArrayLength = Infinity 18 | for (const num in countHash) { 19 | if (countHash[num] === max) { 20 | minSubArrayLength = Math.min(minSubArrayLength, lastOccurance[num] - firstOccurance[num] + 1) 21 | } 22 | } 23 | return minSubArrayLength 24 | 25 | } -------------------------------------------------------------------------------- /03-29/intelligentSubstring.js: -------------------------------------------------------------------------------- 1 | function getSpecialSubstring(s, k, charValue) { 2 | // Write your code here 3 | 4 | let alpha = "abcdefghijklmnopqrstuvwxyz"; 5 | let charType = {}; 6 | 7 | for (let i = 0; i < alpha.length; i++) { 8 | let char = alpha[i] 9 | charType[char] = charValue[i]; 10 | } 11 | debugger 12 | let max = 0; //3 13 | let startingSubString = []; //[0,1,3,4,5] 14 | let startIdx = 0; //3 15 | let last = 0; //1 16 | // giraffe 17 | // k = 2 18 | // 01111001111111111011111111 19 | // Normal characters are in the set {a, f, g, r}. 20 | for (let i = 0; i < s.length; i++) { 21 | let char = s[i] //r 22 | if (charType[char] === '0') { 23 | if (startingSubString.length >= k) { 24 | startIdx++; 25 | } 26 | startingSubString.push(last); 27 | last = i + 1; //6 28 | } 29 | let currLen = i - startingSubString[startIdx] + 1; //3 30 | if (currLen > max) max = currLen; 31 | } 32 | return max; 33 | } -------------------------------------------------------------------------------- /03-29/longestBitonicSubArray.js: -------------------------------------------------------------------------------- 1 | function longestBitonicSubarray(arr) { 2 | // Write your code here 3 | let increasing = new Array(arr.length); //[1,1,2,3,1,1,2] 4 | let decreasing = new Array(arr.length); //[1,0,0,2,1,0,0] 5 | //[null,null,null,null,null,0,0] 6 | 7 | increasing[0] = 1; 8 | decreasing[arr.length - 1] = 0; 9 | 10 | for (let i = 1; i < arr.length; i++) { 11 | increasing[i] = arr[i] >= arr[i - 1] ? increasing[i - 1] + 1 : 1; 12 | } 13 | 14 | for (let i = arr.length - 2; i >= 0; i--) { 15 | decreasing[i] = arr[i] >= arr[i + 1] ? decreasing[i + 1] + 1 : 0; 16 | } 17 | 18 | debugger 19 | let max = increasing[0] + decreasing[0]; 20 | for (let i = 1; i < arr.length; i++) { 21 | max = Math.max(max, decreasing[i] + increasing[i]) 22 | } 23 | return max; 24 | 25 | 26 | } -------------------------------------------------------------------------------- /04-19/firstUniqueChar.js: -------------------------------------------------------------------------------- 1 | function getUniqueCharacter(s) { 2 | // Write your code here 3 | //"statistics" 4 | s = s.split('') 5 | let map = new Map() //{s:2,t:3,a:1,i:1} 6 | for (let i = 0; i < s.length; i++) { 7 | if (!map.has(s[i])) map.set(s[i], 0) 8 | map.set(s[i], map.get(s[i]) + 1) 9 | } 10 | for (let i = 0; i < s.length; i++) { 11 | if (map.get(s[i]) === 1) return i + 1 12 | } 13 | return -1 14 | } -------------------------------------------------------------------------------- /04-19/numberOfMoves.js: -------------------------------------------------------------------------------- 1 | function minMoves(n, startRow, startCol, endRow, endCol) { 2 | //Write your code here 3 | const seenPos = new Set(); 4 | seenPos.add(`${startRow}-${startCol}`); 5 | let count = 0; 6 | const queue = [[startRow, startCol]]; 7 | const directions = [[1, 2], [-1, 2], [1, -2], [-1, -2], [2, 1], [-2, 1], [2, -1], [-2, -1]] 8 | 9 | while (queue.length !== 0) { 10 | let len = queue.length 11 | for (let i = 0; i < len; i++) { 12 | let pos = queue.shift(); 13 | for (let dir of directions) { 14 | let newRow = dir[0] + pos[0]; 15 | let newCol = dir[1] + pos[1]; 16 | if (newRow >= 0 && newCol >= 0 && newRow < n && newCol < n && !seenPos.has(`${newRow}-${newCol}`)) { 17 | if (newRow === endRow && newCol === endCol) return count + 1; 18 | queue.push([newRow, newCol]); 19 | seenPos.add(`${newRow}-${newCol}`); 20 | } 21 | } 22 | } 23 | count++; 24 | } 25 | return -1; 26 | } -------------------------------------------------------------------------------- /04-19/wholeMinuteDelimma.js: -------------------------------------------------------------------------------- 1 | function playlist(songs) { 2 | // Write your code here 3 | //[10, 50, 90, 30] -> [10, 50, 30, 30] 4 | // [20,40] ->[20,40] 5 | debugger 6 | songs = songs.map(time => time % 60) 7 | const counter = {} // {20:1,40:1} 8 | let pairs = 0 //1 9 | songs.forEach(song => { //40 10 | const diff = (60 - song) % 60 //20 11 | if (counter[diff]) pairs += counter[diff] 12 | if (!counter[song]) { 13 | counter[song] = 0 14 | } 15 | counter[song]++ 16 | }) 17 | return pairs 18 | } 19 | -------------------------------------------------------------------------------- /04-26/efficientJanitor.js: -------------------------------------------------------------------------------- 1 | 2 | function efficientJanitor(weight) { 3 | // Write your code here 4 | //. j i. 5 | // [1.01,1.01,1.5,1.99, 2.5] 6 | weight = weight.sort((a, b) => (a - b)); 7 | let i = 0, j = weight.length - 1; 8 | let count = 0; //3 9 | while (i <= j) { 10 | if (weight[i] + weight[j] > 3) { 11 | j--; 12 | count++; 13 | } else if (weight[i] + weight[j] <= 3) { 14 | count++; 15 | i++; 16 | j--; 17 | 18 | } 19 | } 20 | return count; 21 | } 22 | -------------------------------------------------------------------------------- /04-26/reachTheEndInTime.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | function reachTheEnd(grid, maxTime) { 4 | 5 | const visited = new Set().add('0-0') 6 | const dirs = [[1, 0], [-1, 0], [0, -1], [0, 1]] 7 | let queue = [[0, 0, 0]] // [0,1,1] 8 | let gridLen = grid.length 9 | let gridWid = grid[0].length 10 | 11 | while (queue.length) { 12 | const [row, col, time] = queue.shift() // row = 0 col = 0 time = 0 13 | 14 | if (row === gridLen - 1 && col === gridWid - 1 && time <= maxTime) { 15 | return 'Yes' 16 | } 17 | 18 | for (let i = 0; i < dirs.length; i++) { 19 | let newRow = row + dirs[i][0]; //0 20 | let newCol = col + dirs[i][1]; //1 21 | if (validMove(newRow, newCol, gridLen, gridWid, visited, grid)) { 22 | queue.push([newRow, newCol, time + 1]) 23 | } 24 | } 25 | } 26 | 27 | return 'No' 28 | } 29 | 30 | function validMove(row, col, gridLen, gridWid, visited, grid) { 31 | if (visited.has(`${row}-${col}`)) return false 32 | else visited.add(`${row}-${col}`) 33 | 34 | if (row < gridLen && row >= 0 && col < gridWid && col >= 0) { 35 | if (grid[row][col] !== '#') { 36 | return true 37 | } else { 38 | return false 39 | } 40 | } 41 | } 42 | 43 | -------------------------------------------------------------------------------- /04-26/simpleMaxDifference.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | function maxDifference(array) { 4 | // Write your code here 5 | // [7, 1, 2, 5] 6 | let min = Math.max(...array) //1 7 | let profit = 0; //4 8 | array.forEach(val => { 9 | if (val < min) { 10 | min = val 11 | } else if (val - min > profit) { 12 | profit = val - min 13 | } 14 | }) 15 | // i do this for the case where the min and the val meet 16 | // the profit will be 0 so we want to make sure in that case 17 | // it return -1 18 | if (profit === 0) { 19 | return -1 20 | } 21 | return profit 22 | 23 | } 24 | -------------------------------------------------------------------------------- /06-07/bucketFill.js: -------------------------------------------------------------------------------- 1 | function strokesRequired(picture) { 2 | let matrix = picture.map(ele => ele.split("")); 3 | let visited = matrix.map(row => row.map(value => false)); 4 | 5 | let count = 0; 6 | for (let row = 0; row < matrix.length; row++) { 7 | for (let col = 0; col < matrix[0].length; col++) { 8 | if (!visited[row][col]) { 9 | let letter = matrix[row][col]; 10 | color(row, col, letter, visited, matrix); 11 | count++; 12 | } 13 | visited[row][col] = true; 14 | } 15 | } 16 | 17 | return count; 18 | 19 | 20 | } 21 | function color(row, col, letter, visited, matrix) { 22 | let squares = [[row, col]]; 23 | 24 | while (squares.length) { 25 | let node = squares.shift(); 26 | let x = node[0]; 27 | let y = node[1]; 28 | visited[x][y] = true; 29 | let neighbors = getNeighbors(x, y, letter, visited, matrix); 30 | squares = squares.concat(neighbors); 31 | } 32 | } 33 | 34 | function getNeighbors(row, col, letter, visited, matrix) { 35 | let dirs = [[1, 0], [0, 1], [-1, 0], [0, -1]]; 36 | let neighbors = []; 37 | 38 | for (let i = 0; i < dirs.length; i++) { 39 | let newX = row + dirs[i][0]; 40 | let newY = col + dirs[i][1]; 41 | if (newX >= 0 && newX < matrix.length && newY >= 0 && newY < matrix[0].length) { 42 | if (!visited[newX][newY]) { 43 | if (matrix[newX][newY] === letter) { 44 | neighbors.push([newX, newY]); 45 | visited[newX][newY] = true; 46 | } 47 | } 48 | 49 | } 50 | } 51 | 52 | return neighbors; 53 | 54 | 55 | } -------------------------------------------------------------------------------- /06-07/numberOfMoves.js: -------------------------------------------------------------------------------- 1 | function minMoves(n, startRow, startCol, endRow, endCol) { 2 | //Write your code here 3 | const seenPos = new Set(); 4 | seenPos.add(`${startRow}-${startCol}`); 5 | let count = 0; 6 | const queue = [[startRow, startCol]]; 7 | const directions = [[1, 2], [-1, 2], [1, -2], [-1, -2], [2, 1], [-2, 1], [2, -1], [-2, -1]] 8 | 9 | while (queue.length !== 0) { 10 | let len = queue.length 11 | for (let i = 0; i < len; i++) { 12 | let pos = queue.shift(); 13 | for (let dir of directions) { 14 | let newRow = dir[0] + pos[0]; 15 | let newCol = dir[1] + pos[1]; 16 | if (newRow >= 0 && newCol >= 0 && newRow < n && newCol < n && !seenPos.has(`${newRow}-${newCol}`)) { 17 | if (newRow === endRow && newCol === endCol) return count + 1; 18 | queue.push([newRow, newCol]); 19 | seenPos.add(`${newRow}-${newCol}`); 20 | } 21 | } 22 | } 23 | count++; 24 | } 25 | return -1; 26 | } -------------------------------------------------------------------------------- /06-07/scatterPalindrome.js: -------------------------------------------------------------------------------- 1 | function scatterPalindrome(string) { 2 | let result = [] 3 | for (let i = 0; i < string.length; i++) { 4 | let str = string[i]; 5 | let count = 0 6 | for (let j = 0; j < str.length; j++) { 7 | let set = new Set(); 8 | for (let k = j; k < str.length; k++) { 9 | if (set.has(str[k])) { 10 | set.delete(str[k]) 11 | } else { 12 | set.add(str[k]) 13 | } 14 | if (set.size < 2) count++ 15 | } 16 | 17 | } 18 | result.push(count) 19 | } 20 | return result 21 | } -------------------------------------------------------------------------------- /06-07/sellingProducts.js: -------------------------------------------------------------------------------- 1 | function deleteProducts(ids, m) { 2 | // Write your code here 3 | let hashCount = {}; 4 | 5 | for (let i = 0; i < ids.length; i++) { 6 | if (!hashCount[ids[i]]) hashCount[ids[i]] = 0 7 | hashCount[ids[i]]++ 8 | } 9 | 10 | let sortedIds = Object.keys(hashCount).sort((a, b) => hashCount[a] - hashCount[b]); 11 | console.log(sortedIds) 12 | let pointer = 0; 13 | while (m > 0) { 14 | if (hashCount[sortedIds[pointer]] === 0) { 15 | pointer++; 16 | } 17 | hashCount[sortedIds[pointer]]--; 18 | m -= 1 19 | } 20 | 21 | let unique = 0; 22 | 23 | for (let i = 0; i < sortedIds.length; i++) { 24 | if (hashCount[sortedIds[i]] > 0) unique++; 25 | } 26 | 27 | return unique; 28 | 29 | } -------------------------------------------------------------------------------- /06-21/groupAnagrams.js: -------------------------------------------------------------------------------- 1 | function groupAnagrams(words) { 2 | let hash = {} 3 | for (let word of words) { 4 | let sortedWord = word.split('').sort().join('') 5 | if (!hash[sortedWord]) { 6 | hash[sortedWord] = [word] 7 | } else { 8 | hash[sortedWord].push(word) 9 | } 10 | } 11 | return Object.values(hash) 12 | } -------------------------------------------------------------------------------- /06-21/mergeInterval.js: -------------------------------------------------------------------------------- 1 | function getMergedIntervals(intervals) { 2 | // Write your code here 3 | if (intervals.length === 0) return []; 4 | 5 | intervals.sort((a, b) => a[0] - b[0]); 6 | let result = [intervals[0]]; 7 | 8 | for (let i = 1; i < intervals.length; i++) { 9 | let prev = result[result.length - 1]; 10 | let curr = intervals[i]; 11 | if (prev[1] >= curr[0]) { 12 | prev[0] = Math.min(prev[0], curr[0]); 13 | prev[1] = Math.max(prev[1], curr[1]); 14 | } else { 15 | result.push(curr); 16 | } 17 | } 18 | 19 | return result; 20 | 21 | } 22 | 23 | -------------------------------------------------------------------------------- /06-21/slowestKeyPress.js: -------------------------------------------------------------------------------- 1 | function slowestKey(keyTimes) { 2 | // Write your code here 3 | if (keyTimes === null || keyTimes.length === 0) return null; 4 | 5 | let maxTime = -Infinity; 6 | let alphabet = "abcdefghijklmnopqrstuvwxyz"; 7 | let key; 8 | let prevTime = 0; 9 | 10 | for (let i = 0; i < keyTimes.length; i++) { 11 | if (keyTimes[i][1] - prevTime > maxTime) { 12 | maxTime = keyTimes[i][1] - prevTime; 13 | key = alphabet[keyTimes[i][0]]; 14 | } 15 | prevTime = keyTimes[i][1]; 16 | } 17 | return key; 18 | } -------------------------------------------------------------------------------- /06-28/EfficientJanitor.js: -------------------------------------------------------------------------------- 1 | 2 | function efficientJanitor(weight) { 3 | // Write your code here 4 | //. j i. 5 | // [1.01,1.01,1.5,1.99, 2.5] 6 | weight = weight.sort((a, b) => (a - b)); 7 | let i = 0, j = weight.length - 1; 8 | let count = 0; //3 9 | while (i <= j) { 10 | if (weight[i] + weight[j] > 3) { 11 | j--; 12 | count++; 13 | } else if (weight[i] + weight[j] <= 3) { 14 | count++; 15 | i++; 16 | j--; 17 | 18 | } 19 | } 20 | return count; 21 | } 22 | -------------------------------------------------------------------------------- /06-28/FirstUniqueChar.js: -------------------------------------------------------------------------------- 1 | function getUniqueCharacter(s) { 2 | // Write your code here 3 | 4 | let hash = {} 5 | s = s.split('') 6 | for (const char of s) { 7 | if (!hash[char]) hash[char] = 0 8 | hash[char] += 1 9 | } 10 | let unique = [] 11 | Object.keys(hash).forEach(key => { 12 | if (hash[key] === 1) unique.push(key) 13 | }) 14 | for (let i = 0; i < s.length; i++) { 15 | if (unique.includes(s[i])) return i + 1 16 | } 17 | return -1 18 | } -------------------------------------------------------------------------------- /06-28/pickingTickets.js: -------------------------------------------------------------------------------- 1 | function maxTickets(tickets) { 2 | //console.log(tickets) 3 | let sortedArr = tickets.sort((a, b) => a - b); //[2,3,4,13] 4 | 5 | let res = []; 6 | let i = 0; 7 | let arr = []; 8 | while (i < sortedArr.length - 1) { 9 | if (Math.abs(sortedArr[i + 1] - sortedArr[i]) <= 1) { 10 | arr.push(sortedArr[i]); 11 | //console.log(arr) //[2,3] 12 | i++; 13 | } else { 14 | arr.push(sortedArr[i]);//[445] 15 | res.push(arr.length); //3 16 | i++; 17 | arr = []; 18 | } 19 | } 20 | //console.log(res) 21 | return Math.max(...res); 22 | } 23 | -------------------------------------------------------------------------------- /06-28/wholeMinuteDilemma.js: -------------------------------------------------------------------------------- 1 | function playlist(songs) { 2 | // Write your code here 3 | //[10, 50, 90, 30] -> [10, 50, 30, 30] 4 | // [20,40] ->[20,40] 5 | debugger 6 | songs = songs.map(time => time % 60) 7 | const counter = {} // {20:1,40:1} 8 | let pairs = 0 //1 9 | songs.forEach(song => { //40 10 | const diff = (60 - song) % 60 //20 11 | if (counter[diff]) pairs += counter[diff] 12 | if (!counter[song]) { 13 | counter[song] = 0 14 | } 15 | counter[song]++ 16 | }) 17 | return pairs 18 | } 19 | -------------------------------------------------------------------------------- /08-24/minimumSum.js: -------------------------------------------------------------------------------- 1 | function minSum(num, k) { 2 | // Write your code here 3 | // did not pass all test cases due to bad time complexity 4 | while (k !== 0) { 5 | num = num.sort((a, b) => a - b); 6 | let max = num.pop(); 7 | max = Math.ceil(max / 2) 8 | num.push(max) 9 | k-- 10 | } 11 | return num.reduce((a, b) => a + b) 12 | } 13 | -------------------------------------------------------------------------------- /08-24/pileofboxes.js: -------------------------------------------------------------------------------- 1 | function pilesOfBoxes(boxesInPiles) { 2 | // Write your code here 3 | let count = 0; 4 | boxesInPiles.sort((a, b) => b - a); 5 | let i = 0; 6 | while (i < boxesInPiles.length - 1) { 7 | let j = i; 8 | while (boxesInPiles[i] === boxesInPiles[j]) { 9 | j++ 10 | } 11 | count += j 12 | i = j 13 | } 14 | return count 15 | } 16 | 17 | 18 | function getMax(arr) { 19 | arr = arr.sort((a, b) => b - a) 20 | let max = arr[0] 21 | let nextMax; 22 | for (let i = 0; i < arr.length; i++) { 23 | if (arr[i] !== max) { 24 | nextMax = arr[i] 25 | break; 26 | } 27 | } 28 | return [max, nextMax] 29 | 30 | } -------------------------------------------------------------------------------- /08-31/chooseAFlask.js: -------------------------------------------------------------------------------- 1 | function chooseFlask(requirements, flaskTypes, markings) { 2 | requirements = requirements.sort((a, b) => a - b) 3 | let minWaste = [Infinity, -1] 4 | let i = 0 5 | let j = 0 6 | while (i < flaskTypes) { 7 | let currWasteSum = 0 8 | let reqNum = 0 9 | let currFlaskNum = i 10 | while (reqNum < requirements.length && j < markings.length && markings[j][0] === currFlaskNum) { 11 | if (requirements[reqNum] > markings[j][1]) { 12 | j++ 13 | } else { 14 | currWasteSum += markings[j][1] - requirements[reqNum] // currWasteSum = 6 15 | reqNum++ /// j = 1 16 | } // reqNum = 2 17 | } // i = 1 18 | i++ 19 | while (j < markings.length && markings[j][0] === currFlaskNum) { j++ } 20 | if (reqNum !== requirements.length) continue 21 | 22 | if (currWasteSum < minWaste[0]) { 23 | minWaste[0] = currWasteSum 24 | minWaste[1] = currFlaskNum 25 | } 26 | } 27 | 28 | return minWaste[1] 29 | 30 | } -------------------------------------------------------------------------------- /08-31/howmanyWords.js: -------------------------------------------------------------------------------- 1 | function howMany(sentence) { 2 | // Write your code here 3 | let count = 0; 4 | let words = sentence.split(' ') 5 | for (const word of words) { 6 | if (wordCheck(word)) count++ 7 | } 8 | return count 9 | 10 | } 11 | 12 | function wordCheck(word) { 13 | if (word.length === 0) return false 14 | word = word.toLowerCase(); 15 | let alpha = 'abcdefghijklmnopqrstuvwxyz.,?!-'.split('') 16 | let hashAlpha = {} 17 | for (const char of alpha) { 18 | hashAlpha[char] = true 19 | } 20 | for (const char of word) { 21 | if (hashAlpha[char] === undefined) return false 22 | } 23 | return true 24 | } -------------------------------------------------------------------------------- /08-31/longestIncreasingSubsequence.js: -------------------------------------------------------------------------------- 1 | function findLIS(array) { 2 | // result array represents lengths of subsequence starting from specific number 3 | 4 | //[1,4,5,2,6] 5 | let result = new Array(array.length).fill(1);[1, 2, 4, 1, 1] 6 | 7 | for (let i = 1; i < array.length; i++) { 8 | 9 | for (let k = 0; k < i; k++) { 10 | 11 | if (array[k] < array[i]) { 12 | //we make result[i] the max of result of k +1 or the result of i because whichever is the 13 | //max we know it has to take all the values under it anyway 14 | result[i] = Math.max(result[k] + 1, result[i]); 15 | } 16 | 17 | } 18 | 19 | } 20 | 21 | return Math.max(...result); 22 | 23 | 24 | 25 | } 26 | -------------------------------------------------------------------------------- /09-08/bucketFill.js: -------------------------------------------------------------------------------- 1 | function strokesRequired(picture) { 2 | let matrix = picture.map(ele => ele.split("")); 3 | let visited = matrix.map(row => row.map(value => false)); 4 | 5 | let count = 0; 6 | for (let row = 0; row < matrix.length; row++) { 7 | for (let col = 0; col < matrix[0].length; col++) { 8 | if (!visited[row][col]) { 9 | let letter = matrix[row][col]; 10 | color(row, col, letter, visited, matrix); 11 | count++; 12 | } 13 | visited[row][col] = true; 14 | } 15 | } 16 | 17 | return count; 18 | 19 | 20 | } 21 | function color(row, col, letter, visited, matrix) { 22 | let squares = [[row, col]]; 23 | 24 | while (squares.length) { 25 | let node = squares.shift(); 26 | let x = node[0]; 27 | let y = node[1]; 28 | visited[x][y] = true; 29 | let neighbors = getNeighbors(x, y, letter, visited, matrix); 30 | squares = squares.concat(neighbors); 31 | } 32 | } 33 | 34 | function getNeighbors(row, col, letter, visited, matrix) { 35 | let dirs = [[1, 0], [0, 1], [-1, 0], [0, -1]]; 36 | let neighbors = []; 37 | 38 | for (let i = 0; i < dirs.length; i++) { 39 | let newX = row + dirs[i][0]; 40 | let newY = col + dirs[i][1]; 41 | if (newX >= 0 && newX < matrix.length && newY >= 0 && newY < matrix[0].length) { 42 | if (!visited[newX][newY]) { 43 | if (matrix[newX][newY] === letter) { 44 | neighbors.push([newX, newY]); 45 | visited[newX][newY] = true; 46 | } 47 | } 48 | 49 | } 50 | } 51 | 52 | return neighbors; 53 | 54 | 55 | } -------------------------------------------------------------------------------- /09-08/perfectSubstring.js: -------------------------------------------------------------------------------- 1 | // does not pass all test cases due to bad time complexity 2 | function perfectSubstring(s, k) { 3 | // Write your code here 4 | let result = []; 5 | for (let i = 0; i < s.length; i++) { 6 | for (let j = i + 1; j < s.length + 1; j++) { 7 | result.push(s.slice(i, j)); 8 | } 9 | } 10 | let count = 0 11 | result.forEach(str => { 12 | if (countChars(str, k)) count++ 13 | }) 14 | return count 15 | 16 | } 17 | function countChars(str, k) { 18 | let hash = {} 19 | for (let i = 0; i < str.length; i++) { 20 | if (!hash[str[i]]) hash[str[i]] = 0 21 | hash[str[i]]++ 22 | } 23 | return Object.values(hash).every(value => value === k) 24 | } -------------------------------------------------------------------------------- /09-08/sellingProducts.js: -------------------------------------------------------------------------------- 1 | function deleteProducts(ids, m) { 2 | // Write your code here 3 | let hashCount = {}; 4 | 5 | for (let i = 0; i < ids.length; i++) { 6 | if (!hashCount[ids[i]]) hashCount[ids[i]] = 0 7 | hashCount[ids[i]]++ 8 | } 9 | 10 | let sortedIds = Object.keys(hashCount).sort((a, b) => hashCount[a] - hashCount[b]); 11 | console.log(sortedIds) 12 | let pointer = 0; 13 | while (m > 0) { 14 | if (hashCount[sortedIds[pointer]] === 0) { 15 | pointer++; 16 | } 17 | hashCount[sortedIds[pointer]]--; 18 | m -= 1 19 | } 20 | 21 | let unique = 0; 22 | 23 | for (let i = 0; i < sortedIds.length; i++) { 24 | if (hashCount[sortedIds[i]] > 0) unique++; 25 | } 26 | 27 | return unique; 28 | 29 | } -------------------------------------------------------------------------------- /09-14/competitiveGaming.js: -------------------------------------------------------------------------------- 1 | function numPlayers(k, scores) { 2 | //[100, 100, 50, 25] k = 3 3 | let sortedScores = scores.sort((a, b) => b - a); 4 | let ranks = new Array(sortedScores.length).fill(0); //[1,1,0,0] 5 | ranks[0] = 1; 6 | 7 | let pos = 2; //4 8 | for (let i = 1; i < sortedScores.length; i++) { 9 | if (sortedScores[i] === sortedScores[i - 1]) { 10 | ranks[i] = ranks[i - 1]; 11 | } else { 12 | ranks[i] = pos; 13 | } 14 | pos++; 15 | } 16 | 17 | let count = 0; 18 | for (let i = 0; i < ranks.length; i++) { 19 | if (ranks[i] <= k) { 20 | if (sortedScores[i] > 0) count++; 21 | } 22 | } 23 | 24 | return count; 25 | 26 | } -------------------------------------------------------------------------------- /09-14/numberOfMoves.js: -------------------------------------------------------------------------------- 1 | function minMoves(n, startRow, startCol, endRow, endCol) { 2 | //Write your code here 3 | const seenPos = new Set(); 4 | seenPos.add(`${startRow}-${startCol}`); 5 | let count = 0; 6 | const queue = [[startRow, startCol]]; 7 | const directions = [[1, 2], [-1, 2], [1, -2], [-1, -2], [2, 1], [-2, 1], [2, -1], [-2, -1]] 8 | 9 | while (queue.length !== 0) { 10 | let len = queue.length 11 | for (let i = 0; i < len; i++) { 12 | let pos = queue.shift(); 13 | for (let dir of directions) { 14 | let newRow = dir[0] + pos[0]; 15 | let newCol = dir[1] + pos[1]; 16 | if (newRow >= 0 && newCol >= 0 && newRow < n && newCol < n && !seenPos.has(`${newRow}-${newCol}`)) { 17 | if (newRow === endRow && newCol === endCol) return count + 1; 18 | queue.push([newRow, newCol]); 19 | seenPos.add(`${newRow}-${newCol}`); 20 | } 21 | } 22 | } 23 | count++; 24 | } 25 | return -1; 26 | 27 | 28 | 29 | } -------------------------------------------------------------------------------- /09-14/simpleMaxDifference.js: -------------------------------------------------------------------------------- 1 | function maxDifference(array) { 2 | // Write your code here 3 | let min = Math.max(...array) //7 4 | let profit = -1; //4 5 | array.forEach(val => { 6 | 7 7 | if (val < min) { 8 | min = val //min =1 9 | } else if (val - min > profit) { 10 | profit = val - min 11 | } 12 | }) 13 | // i do this for the case where the min and the val meet 14 | // the profit will be 0 so we want to make sure in that case 15 | // it return -1 16 | if (profit === 0) { 17 | return -1 18 | } 19 | return profit 20 | 21 | } -------------------------------------------------------------------------------- /09-21/almostSameStrings.js: -------------------------------------------------------------------------------- 1 | function areAlmostEquivalent(s, t) { 2 | // Write your code here 3 | let result = [] 4 | for (let i = 0; i < s.length; i++) { 5 | if (helper(s[i], t[i])) { 6 | result.push('YES') 7 | } else { 8 | result.push('NO') 9 | } 10 | } 11 | return result 12 | } 13 | 14 | function helper(str1, str2) { 15 | if (str1.length !== str2.length) return false 16 | let hash = {} 17 | for (let i = 0; i < str1.length; i++) { 18 | if (!hash[str1[i]]) { 19 | hash[str1[i]] = 0 20 | } 21 | hash[str1[i]] += 1 22 | } 23 | for (let i = 0; i < str2.length; i++) { 24 | if (!hash[str2[i]]) { 25 | hash[str2[i]] = 0 26 | } else { 27 | hash[str2[i]] -= 1 28 | } 29 | 30 | } 31 | return Object.values(hash).every(val => Math.abs(val) <= 3) 32 | } -------------------------------------------------------------------------------- /09-21/findtheFactor.js: -------------------------------------------------------------------------------- 1 | function pthFactor(n, p) { 2 | // Write your code here 3 | let result = [] 4 | let div = 1 5 | while (div * div <= n) { 6 | if (n % div === 0) { 7 | result.push(div); 8 | if (n / div !== div) { 9 | result.push(n / div); 10 | } 11 | 12 | } 13 | div++; 14 | } 15 | result = result.sort((a, b) => a - b) 16 | return result[p - 1] ? result[p - 1] : 0 17 | 18 | } -------------------------------------------------------------------------------- /09-21/scatterPalindrome.js: -------------------------------------------------------------------------------- 1 | function scatterPalindrome(string) { 2 | let result = [] 3 | for (let i = 0; i < string.length; i++) { 4 | let str = string[i]; 5 | let count = 0 6 | for (let j = 0; j < str.length; j++) { 7 | let set = new Set(); 8 | for (let k = j; k < str.length; k++) { 9 | if (set.has(str[k])) { 10 | set.delete(str[k]) 11 | } else { 12 | set.add(str[k]) 13 | } 14 | if (set.size < 2) count++ 15 | } 16 | 17 | } 18 | result.push(count) 19 | } 20 | return result 21 | } -------------------------------------------------------------------------------- /09-21/throttlingGateway.js: -------------------------------------------------------------------------------- 1 | function droppedRequests(requestTime) { 2 | // Write your code here 3 | // [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, 11, 11, 11, 11 ] 4 | const uniqueSetoftime = new Set(requestTime) //{1,2,3,4,5,6,11} 5 | const freqs = {} 6 | let dropRequests = 0 7 | 8 | for (let i = 0; i < requestTime.length; i++) { 9 | const reqTime = requestTime[i] 10 | if (!freqs[reqTime]) { 11 | freqs[reqTime] = { ones: 0, tens: 0, mins: 0 } 12 | } 13 | freqs[reqTime].ones++ 14 | for (let j = 0; j < 60; j++) { 15 | const newRT = reqTime + j 16 | if (!uniqueSetoftime.has(newRT)) continue 17 | if (!freqs[newRT]) { 18 | freqs[newRT] = { ones: 0, tens: 0, mins: 0 } 19 | } 20 | if (j < 10) freqs[newRT].tens++ 21 | freqs[newRT].mins++ 22 | } 23 | if (freqs[reqTime].ones > 3 || freqs[reqTime].tens > 20 || freqs[reqTime].mins > 60) dropRequests++ 24 | } 25 | return dropRequests 26 | 27 | } -------------------------------------------------------------------------------- /09-28/Price_check.js: -------------------------------------------------------------------------------- 1 | function priceCheck(products, productPrices, productSold, soldPrice) { 2 | // Write your code here 3 | let errors = 0; 4 | let hash = {}; 5 | 6 | for (let i = 0; i < products.length; i++) { 7 | hash[products[i]] = productPrices[i] 8 | } 9 | 10 | for (let i = 0; i < productSold.length; i++) { 11 | if (hash[productSold[i]] !== soldPrice[i]) { 12 | errors++ 13 | } 14 | } 15 | 16 | return errors 17 | 18 | } -------------------------------------------------------------------------------- /09-28/ProfitTargets.js: -------------------------------------------------------------------------------- 1 | function stockPairs(stocksProfit, target) { 2 | // Write your code here 3 | let sorted = stocksProfit.sort((a, b) => a - b) 4 | let uniqueCombos = new Set(); 5 | let count = 0; 6 | 7 | let i = 0; 8 | let j = sorted.length - 1 9 | while (i < j) { 10 | let sum = sorted[i] + sorted[j] 11 | if (sum === target) { 12 | let str = `${sorted[i]}-${sorted[j]}` 13 | if (!uniqueCombos.has(str)) { 14 | uniqueCombos.add(str) 15 | count++ 16 | } 17 | j-- 18 | i++ 19 | } else if (sum > target) { 20 | j-- 21 | } else { 22 | i++ 23 | } 24 | } 25 | 26 | return count; 27 | 28 | } -------------------------------------------------------------------------------- /09-28/ReachTheEndInTime.js: -------------------------------------------------------------------------------- 1 | function reachTheEnd(grid, maxTime) { 2 | const visited = new Set().add('0-0') 3 | const dirs = [[1, 0], [-1, 0], [0, -1], [0, 1]] 4 | let queue = [[0, 0, 0]] 5 | let minTime = Infinity 6 | let gridLen = grid.length 7 | let gridWid = grid[0].length 8 | 9 | while (queue.length) { 10 | const pathNodes = [] 11 | for (let i = 0; i < queue.length; i++) { 12 | const [row, col, time] = queue[i] 13 | 14 | if (row === gridLen - 1 && col === gridWid - 1) { 15 | minTime = Math.min(minTime, time) 16 | continue 17 | } 18 | 19 | for (let i = 0; i < dirs.length; i++) { 20 | let newRow = row + dirs[i][0]; 21 | let newCol = col + dirs[i][1]; 22 | if (validMove(newRow, newCol, gridLen, gridWid, visited, grid)) { 23 | pathNodes.push([newRow, newCol, time + 1]) 24 | } 25 | } 26 | } 27 | queue = pathNodes 28 | } 29 | 30 | return minTime <= maxTime ? 'Yes' : 'No' 31 | } 32 | 33 | function validMove(row, col, gridLen, gridWid, visited, grid) { 34 | if (visited.has(`${row}-${col}`)) return false 35 | else visited.add(`${row}-${col}`) 36 | 37 | if (row < gridLen && row >= 0 && col < gridWid && col >= 0) { 38 | if (grid[row][col] !== '#') { 39 | return true 40 | } else { 41 | return false 42 | } 43 | } 44 | 45 | 46 | } -------------------------------------------------------------------------------- /10-05/AnagramDifference.js: -------------------------------------------------------------------------------- 1 | function getMinimumDifference(a, b) { 2 | // Write your code here 3 | let result = [] 4 | for (let i = 0; i < a.length; i++) { 5 | if (a[i].length !== b[i].length) result.push(-1) 6 | else result.push(anagram(a[i], b[i])) 7 | } 8 | return result 9 | } 10 | //tea 11 | 12 | //{t:1,e:1,a:1} 13 | 14 | //too 15 | 16 | //{t:0,e:1,a:1,o:-1} 17 | 18 | function anagram(word1, word2) { 19 | let hash = {} 20 | word1.split('').forEach(char => { 21 | if (!hash[char]) hash[char] = 0 22 | hash[char] += 1 23 | }) 24 | word2.split('').forEach(char => { 25 | if (hash[char]) { 26 | hash[char] -= 1 27 | } else if (!hash[char]) { 28 | hash[char] = 0 29 | } 30 | }) 31 | Object.keys(hash).forEach(char => { 32 | if (hash[char] < 0) { 33 | hash[char] = -(hash[char]) 34 | } 35 | }) 36 | return sum(Object.values(hash)) 37 | } 38 | 39 | function sum(array) { 40 | return array.reduce((a, b) => a + b) 41 | } -------------------------------------------------------------------------------- /10-05/CountingPairs.js: -------------------------------------------------------------------------------- 1 | 2 | function countPairs(numbers, k) { 3 | // set to save the values of a where a = b - k 4 | const aValues = new Set() //{0,1} 5 | for (let i = 0; i < numbers.length; i++) { 6 | let a = numbers[i] - k // 7 | if (aValues.has(a)) { 8 | continue 9 | } else { 10 | aValues.add(a) 11 | } 12 | } 13 | 14 | let count = 0 15 | for (let i = 0; i < numbers.length; i++) { 16 | if (aValues.has(numbers[i])) { //{0} 17 | count++ 18 | aValues.delete(numbers[i]) 19 | } 20 | } 21 | return count 22 | } 23 | -------------------------------------------------------------------------------- /10-05/ShoppingCartBilling.js: -------------------------------------------------------------------------------- 1 | 2 | function findLowestPrice(products, discounts) { 3 | const discountMap = createDiscountMap(discounts) 4 | let total = 0 5 | let t2 = 0 6 | 7 | for (let i = 0; i < products.length; i++) { 8 | const price = parseInt(products[i][0]) 9 | t2 += price 10 | let best = price 11 | for (let j = 1; j < products[i].length; j++) { 12 | const newPrice = calcDiscountPrice(discountMap, products[i][j], price) 13 | best = Math.min(best, newPrice) 14 | } 15 | total += best 16 | } 17 | 18 | return total 19 | } 20 | 21 | const calcDiscountPrice = (discountMap, name, originalPrice) => { 22 | if (discountMap[name] === undefined) return originalPrice 23 | 24 | switch (discountMap[name].type) { 25 | case 0: 26 | return discountMap[name].val 27 | 28 | case 1: 29 | return Math.round(originalPrice - (originalPrice * (discountMap[name].val / 100))) 30 | 31 | case 2: 32 | return Math.round(originalPrice - discountMap[name].val) 33 | 34 | default: 35 | return originalPrice 36 | } 37 | } 38 | 39 | const createDiscountMap = (arr) => { 40 | const map = {} 41 | for (let i = 0; i < arr.length; i++) { 42 | const item = arr[i] 43 | map[item[0]] = { type: parseInt(item[1]), val: parseInt(item[2]) } 44 | } 45 | return map 46 | } -------------------------------------------------------------------------------- /10-05/maximumRatingSum.js: -------------------------------------------------------------------------------- 1 | function maximumSum(arr) { 2 | // Write your code here 3 | let maxHere = arr[0] //3 4 | let maxSofar = arr[0] //10 5 | for (let i = 1; i < arr.length; i++) { 6 | let num = arr[i] 7 | maxHere = Math.max(num, maxHere + num) 8 | maxSofar = Math.max(maxHere, maxSofar) 9 | } 10 | return maxSofar 11 | 12 | } 13 | -------------------------------------------------------------------------------- /10-12/ArrayGame.js: -------------------------------------------------------------------------------- 1 | function countMoves(numbers) { 2 | // Write your code here 3 | let min = Math.min(...numbers) 4 | let numOfMoves = 0 5 | for (let num of numbers) { 6 | numOfMoves += (num - min) 7 | } 8 | return numOfMoves 9 | } 10 | -------------------------------------------------------------------------------- /10-12/EvenSubarray.js: -------------------------------------------------------------------------------- 1 | //not the optimal solution 2 | function evenSubarray(numbers, k) { 3 | // Write your code here 4 | let result = {} 5 | for (let i = 0; i < numbers.length; i++) { 6 | for (let j = i + 1; j < numbers.length + 1; j++) { 7 | if (!result[numbers.slice(i, j)]) { 8 | result[numbers.slice(i, j)] = true; 9 | } 10 | } 11 | } 12 | 13 | let count = 0 14 | Object.keys(result).forEach(subArr => { 15 | if (countOdd(subArr, k)) { 16 | count++ 17 | } 18 | }) 19 | return count 20 | } 21 | function countOdd(subArr, k) { 22 | let count = 0; 23 | subArr = subArr.split(',') 24 | for (let i = 0; i < subArr.length; i++) { 25 | let num = subArr[i] 26 | if (num % 2 !== 0) { 27 | count++ 28 | } 29 | } 30 | return count <= k ? true : false 31 | 32 | } -------------------------------------------------------------------------------- /10-12/WebsitePagination.js: -------------------------------------------------------------------------------- 1 | function fetchItemsToDisplay(items, sortParameter, sortOrder, itemsPerPage, pageNumber) { 2 | // Write your code here 3 | 4 | // [['item1', '10', '15'], ['item2', '3', '4'], ['item3', '17', '8']] 5 | // sortParameter = 1 (relevance) 6 | // sortOrder = 0 (ascending) 7 | // itemsPerPage = 2 8 | // pageNumber = 1 9 | 10 | //items = [['item2', '3', '4'], ['item1', '10', '15'], ['item3', '17', '8']] 11 | 12 | 13 | if (sortParameter === 0) { 14 | items.sort((a, b) => (a[0] < b[0]) ? -1 : 1); 15 | } else { 16 | items.sort((a, b) => a[sortParameter] - b[sortParameter]); 17 | } 18 | 19 | if (sortOrder === 1) { 20 | items = items.reverse(); 21 | } 22 | let i = pageNumber * itemsPerPage; //1*0 =0 23 | let pageItems = []; 24 | while (i < items.length && pageItems.length < itemsPerPage) { 25 | pageItems.push(items[i][0]); 26 | i++; 27 | } 28 | return pageItems; 29 | } -------------------------------------------------------------------------------- /10-19/efficientCost.js: -------------------------------------------------------------------------------- 1 | //bad time complexity passes only 6/13 test cases 2 | 3 | function calculateCost(arr, k, memo = {}) { 4 | // // Write your code here 5 | 6 | if (!arr.length) return 0; 7 | let solutions = []; 8 | for (let i = 1; i <= k; i++) { 9 | let temp = arr.slice(0, i); 10 | let max = Math.max(...temp); 11 | solutions.push(max + calculateCost(arr.slice(i), k)); 12 | if (i === arr.length) break; 13 | } 14 | return Math.min(...solutions); 15 | } 16 | -------------------------------------------------------------------------------- /10-19/efficientStudy.js: -------------------------------------------------------------------------------- 1 | function maximumLearning(iv, articles, p) { 2 | // Write your code here 3 | 4 | const dp = [new Array(p + 1).fill(0)]; 5 | // create a 2D array 6 | // each row will represent each page amount in the articles array 7 | for (let i = 0; i < articles.length; i += 1) { 8 | dp.push(new Array(p + 1).fill(0)); 9 | } 10 | // loop through each row of the dp array 11 | for (let i = 1; i < dp.length; i += 1) { 12 | const pageAmt = articles[i - 1] * 2; 13 | const currValue = iv[i - 1]; 14 | // go thru each page starting from 0 to the max pages, p 15 | for (let currPageMax = 0; currPageMax <= p; currPageMax += 1) { 16 | // if the current pages you can read is less than j (the current max pages) 17 | if (pageAmt <= currPageMax) { 18 | // find the max 19 | dp[i][currPageMax] = Math.max( 20 | dp[i - 1][currPageMax], 21 | dp[i - 1][currPageMax - pageAmt] + currValue 22 | ); 23 | } else { 24 | dp[i][currPageMax] = dp[i - 1][currPageMax]; 25 | } 26 | } 27 | } 28 | return dp[articles.length][p]; 29 | } 30 | -------------------------------------------------------------------------------- /10-19/gameSegments.js: -------------------------------------------------------------------------------- 1 | function playSegments(coins) { 2 | let player1 = 0; //0 3 | let player2 = 0; //2 4 | for (let i = 0; i < coins.length; i++) { 5 | if (coins[i] === 0) { 6 | player2--; 7 | } else { 8 | player2++; 9 | } 10 | } 11 | for (let i = 0; i < coins.length; i++) { 12 | if (player1 > player2) { 13 | return i; 14 | } 15 | if (coins[i] === 0) { 16 | player2++; 17 | player1--; 18 | } else { 19 | player2--; 20 | player1++; 21 | } 22 | } 23 | return -1; 24 | } 25 | -------------------------------------------------------------------------------- /10-26/efficentJanito.js: -------------------------------------------------------------------------------- 1 | function efficientJanitor(weight) { 2 | // Write your code here 3 | weight = weight.sort((a, b) => (a - b)); 4 | let i = 0, j = weight.length - 1; 5 | let count = 0; 6 | while (i <= j) { 7 | if (weight[i] + weight[j] <= 3) { 8 | count++; 9 | i++; 10 | j--; 11 | } else if (weight[i] + weight[j] > 3) { 12 | j--; 13 | count++; 14 | } 15 | } 16 | return count; 17 | } -------------------------------------------------------------------------------- /10-26/minimumMoves.js: -------------------------------------------------------------------------------- 1 | function minimumMoves(arr1, arr2) { 2 | // Write your code here 3 | let count = 0; 4 | for (let i = 0; i < arr1.length; i++) { 5 | let int1 = arr1[i]; 6 | let int2 = arr2[i]; 7 | count += helper(int1, int2) 8 | } 9 | return count; 10 | } 11 | function helper(int1, int2) { // %10 -> GeWei /10 12 | let num = 0; 13 | while (int1 !== 0) { 14 | num += Math.abs(int1 % 10 - int2 % 10); //2 15 | int1 = Math.floor(int1 / 10); 16 | int2 = Math.floor(int2 / 10); 17 | } 18 | return num; 19 | } -------------------------------------------------------------------------------- /10-26/parkingTickets.js: -------------------------------------------------------------------------------- 1 | function maxTickets(tickets) { 2 | //console.log(tickets) 3 | let sortedArr = tickets.sort((a, b) => a - b); //[2,3,4,13] 4 | 5 | let res = []; 6 | let i = 0; 7 | let arr = []; 8 | while (i < sortedArr.length - 1) { 9 | if (Math.abs(sortedArr[i + 1] - sortedArr[i]) <= 1) { 10 | arr.push(sortedArr[i]); 11 | //console.log(arr) //[2,3] 12 | i++; 13 | } else { 14 | arr.push(sortedArr[i]);//[445] 15 | res.push(arr.length); //3 16 | i++; 17 | arr = []; 18 | } 19 | } 20 | //console.log(res) 21 | return Math.max(...res); 22 | } 23 | -------------------------------------------------------------------------------- /11-16/TwinStrings.js: -------------------------------------------------------------------------------- 1 | function twins(a, b) { 2 | return [...Array(a.length).keys()].map(i => forSingleCase(a[i], b[i])); 3 | } 4 | 5 | function forSingleCase(str1, str2) { 6 | if (str2.length !== str1.length) return "No"; 7 | const evenFreqs = {}; 8 | const oddFreqs = {}; 9 | 10 | for (let i = 0; i < str1.length; i++) { 11 | if (i % 2 === 0) { 12 | updateFreqs(evenFreqs, str1[i], str2[i]); 13 | } else { 14 | updateFreqs(oddFreqs, str1[i], str2[i]); 15 | } 16 | } 17 | return areAllFreqsZero(evenFreqs, oddFreqs) ? "Yes" : "No"; 18 | } 19 | 20 | function updateFreqs(freqHash, char1, char2) { 21 | if (char1 in freqHash) { 22 | freqHash[char1]++; 23 | } else { 24 | freqHash[char1] = 1; 25 | } 26 | if (char2 in freqHash) { 27 | freqHash[char2]--; 28 | } else { 29 | freqHash[char2] = -1; 30 | } 31 | } 32 | 33 | function areAllFreqsZero(evenFreqs, oddFreqs) { 34 | const allFreqs = Object.values(evenFreqs).concat(Object.values(oddFreqs)); 35 | for (const freq of allFreqs) { 36 | if (freq !== 0) return false; 37 | } 38 | return true; 39 | } -------------------------------------------------------------------------------- /11-16/busStrand.js: -------------------------------------------------------------------------------- 1 | 2 | function kthPerson(k, p, q) { 3 | return q.map(time => forSingleQuery(k, p, time)); 4 | } 5 | 6 | function forSingleQuery(cap, people, time) { 7 | let numQueued = 0; 8 | for (let i = 0; i < people.length; i++) { 9 | if (people[i] >= time) numQueued++; 10 | if (numQueued === cap) return i + 1; 11 | 12 | const peopleRemaining = people.length - i - 1; 13 | const peopleNeededToFill = cap - numQueued; 14 | if (peopleRemaining < peopleNeededToFill) return 0; 15 | } 16 | } -------------------------------------------------------------------------------- /11-16/findTheSequenceSum.js: -------------------------------------------------------------------------------- 1 | function getSequenceSum(i, j, k) { 2 | let num = i; 3 | let sum = 0; 4 | while (num < j) { 5 | sum += num++; 6 | } 7 | while (num >= k) { 8 | sum += num--; 9 | } 10 | return sum; 11 | } 12 | -------------------------------------------------------------------------------- /11-2/autoscalePolicy.js: -------------------------------------------------------------------------------- 1 | function finalInstances(instances, averageUtil) { 2 | const halfMaxInstances = 10 ** 8 3 | let i = 0 4 | 5 | while (i < averageUtil.length) { 6 | const u = averageUtil[i] 7 | 8 | if (u < 25 && instances > 1) { 9 | instances = Math.ceil(instances / 2) 10 | i += 10 11 | } else if (u > 60 && instances <= halfMaxInstances) { 12 | instances *= 2 13 | i += 10 14 | } 15 | i++ 16 | } 17 | 18 | return instances 19 | } 20 | -------------------------------------------------------------------------------- /11-2/teamFormation.js: -------------------------------------------------------------------------------- 1 | function countTeams(skills, minPlayers, minLevel, maxLevel) { 2 | let numValid = 0 3 | skills.forEach(skill => { 4 | if (skill >= minLevel && skill <= maxLevel) numValid++ 5 | }) 6 | let possibleTeams = 0 7 | 8 | for (let i = minPlayers; i <= numValid; i++) { 9 | const [numToChoose, total] = [i, numValid] 10 | const moreTeams = factorialize(total) / (factorialize(numToChoose) * factorialize(total - numToChoose)) 11 | possibleTeams += moreTeams 12 | } 13 | 14 | return possibleTeams 15 | } 16 | 17 | function factorialize(num) { 18 | if (num < 2) return 1 19 | for (let i = num - 1; i >= 1; i--) num *= i 20 | return num; 21 | } -------------------------------------------------------------------------------- /11-30/minimumSwaps.js: -------------------------------------------------------------------------------- 1 | function minimumSwaps(popularity) { 2 | // Write your code here 3 | 4 | // [4, 3, 2, 1] 5 | let numSwaps = 0; 6 | let i = 0; 7 | while (i < popularity.length) { 8 | let diff = popularity.length - popularity[i] 9 | if (diff === i) { 10 | i++ 11 | continue 12 | } 13 | swap(popularity, diff, i) 14 | numSwaps++ 15 | } 16 | return numSwaps 17 | } 18 | 19 | function swap(arr, i, j) { 20 | [arr[i], arr[j]] = [arr[j], arr[i]] 21 | } -------------------------------------------------------------------------------- /11-30/rumbleInTokyo.js: -------------------------------------------------------------------------------- 1 | function getMinimumBlows(height) { 2 | if (height.length < 3) return 1 3 | 4 | const minHit = new Array(height.length) 5 | 6 | let hits = 0 //5 7 | let currHeight = 0 //1 8 | for (let i = 0; i < height.length; i++) { //1 9 | let building = height[i] 10 | if (!hits || building < currHeight) hits++ 11 | currHeight = building 12 | minHit[i] = hits 13 | } 14 | debugger 15 | v 16 | //[6,5,4,3,4,5,4,5,6] 17 | hits = 0 //3 18 | currHeight = 0 //3 19 | for (let i = height.length - 1; i >= 0; i--) {//3 20 | let building = height[i] 21 | if (!hits || building < currHeight) hits++ 22 | currHeight = building 23 | minHit[i] += hits 24 | } 25 | 26 | return Math.min(...minHit) 27 | } -------------------------------------------------------------------------------- /11-30/wholeMinuteDilemma.js: -------------------------------------------------------------------------------- 1 | function playlist(songs) { 2 | // Write your code here 3 | //[10, 50, 90, 30, 30] 4 | songs = songs.map(time => time % 60) 5 | const counter = {} //{10:1,30:2} 6 | let pairs = 0 //4 7 | songs.forEach(song => { //[10,50,30,30,30] 8 | const diff = (60 - song) % 60 9 | if (counter[diff]) pairs += counter[diff] 10 | if (!counter[song]) { 11 | counter[song] = 0 12 | } 13 | counter[song]++ 14 | }) 15 | return pairs 16 | 17 | } 18 | -------------------------------------------------------------------------------- /11-9/counterfeitCurrency.js: -------------------------------------------------------------------------------- 1 | function countCounterfeit(serialNumber) { 2 | const denoms = new Set(['10', '20', '50', '100', '200', '500', '1000']); 3 | let value = 0; 4 | for (let i = 0; i < serialNumber.length; i++) { 5 | let note = serialNumber[i]; 6 | if (note.length < 10 || note.length > 12) continue; 7 | if (!/[A-Z]/.test(note[0]) || !/[A-Z]/.test(note[1]) || !/[A-Z]/.test(note[2])) { 8 | continue; 9 | } 10 | if (note[0] === note[1] || note[0] === note[2] || note[1] === note[2]) continue; 11 | let year = note.slice(3, 7); 12 | if (isNaN(year) || parseInt(year) > 2019 || parseInt(year) < 1900) continue; 13 | if (!/[A-Z]/.test(note[note.length - 1])) continue; 14 | let val = note.slice(7, note.length - 1); 15 | if (!denoms.has(val)) continue; 16 | // console.log(note, val) 17 | value += parseInt(val); 18 | } 19 | return value; 20 | } -------------------------------------------------------------------------------- /11-9/liftingWeight.js: -------------------------------------------------------------------------------- 1 | function weightCapacity(weights, maxCapacity) { 2 | let res = 0; 3 | weights.sort((a, b) => a - b); 4 | const memo = {}; 5 | return helper(0, 0); 6 | 7 | function helper(prevWeight, i) { 8 | if (i >= weights.length) return prevWeight; 9 | let key = `${prevWeight}-${i}`; 10 | if (key in memo) return memo[key]; 11 | let curWeight = weights[i]; 12 | if (prevWeight + curWeight > maxCapacity) return prevWeight; 13 | 14 | let option1 = helper(prevWeight + curWeight, i + 1); 15 | let option2 = helper(prevWeight, i + 1); 16 | memo[key] = Math.max(option1, option2); 17 | return memo[key]; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /11-9/wordCompression.js: -------------------------------------------------------------------------------- 1 | function compressWord(word, k) { 2 | const stack = []; 3 | stack.push([word[0], 1]); 4 | for (let i = 1; i < word.length; i++) { 5 | let char = word[i]; 6 | let top = stack[stack.length - 1] || []; 7 | if (top.length && top[0] === char) { 8 | if (top[1] === k - 1) { 9 | stack.pop(); 10 | } else { 11 | top[1]++; 12 | } 13 | } else { 14 | stack.push([char, 1]); 15 | } 16 | } 17 | let res = ''; 18 | for (let ele of stack) { 19 | res += ele[0].repeat(ele[1]); 20 | } 21 | return res; 22 | } -------------------------------------------------------------------------------- /12-14/blah.js: -------------------------------------------------------------------------------- 1 | function groupAnagrams(words){ 2 | let hash = {} 3 | for(let word of words){ 4 | let sortedWord = word.split('').sort().join('') 5 | if(!hash[sortedWord]){ 6 | hash[sortedWord] = [word] 7 | }else{ 8 | hash[sortedWord].push(word) 9 | } 10 | } 11 | return Object.values(hash) 12 | } -------------------------------------------------------------------------------- /12-14/gameWinner.js: -------------------------------------------------------------------------------- 1 | function gameWinner(colors) { 2 | // Write your code here 3 | let wendy = 0 4 | let bob = 0 5 | for (let i = 1; i < colors.length; i++) { 6 | if (colors[i] === 'w' && colors[i - 1] === colors[i] && colors[i + 1] === colors[i]) { 7 | wendy += 1 8 | } 9 | if (colors[i] === 'b' && colors[i - 1] === colors[i] && colors[i + 1] === colors[i]) { 10 | bob += 1 11 | } 12 | } 13 | if (wendy > bob) { 14 | return 'wendy' 15 | } else { 16 | return 'bob' 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /12-14/groupingDigits.js: -------------------------------------------------------------------------------- 1 | function minMoves(arr) { 2 | // Write your code here 3 | debugger 4 | let countOf1s = 0; 5 | let countOf0s = 0; 6 | let swap1sToLeft = 0; 7 | let swap0sToLeft = 0; 8 | 9 | for (const num of arr) { 10 | if (num === 0) { 11 | countOf1s += 1; 12 | swap0sToLeft += countOf0s; 13 | } else { 14 | countOf0s += 1; 15 | swap1sToLeft += countOf1s; 16 | } 17 | } 18 | return Math.min(swap0sToLeft, swap1sToLeft) 19 | 20 | } 21 | -------------------------------------------------------------------------------- /12-14/profitTargets.js: -------------------------------------------------------------------------------- 1 | function stockPairs(stocksProfit, target) { 2 | // Write your code here 3 | let stocks = new Set() 4 | let count = 0 5 | let pairs = new Set() 6 | for (let num of stocksProfit) { 7 | let diff = target - num 8 | if (stocks.has(diff) && !pairs.has(`${num}-${diff}`) && !pairs.has(`${diff}-${num}`)) { 9 | count++ 10 | pairs.add(`${diff}-${num}`); 11 | } 12 | stocks.add(num); 13 | } 14 | return count 15 | } 16 | -------------------------------------------------------------------------------- /12-7/arrayReduction.js: -------------------------------------------------------------------------------- 1 | function reductionCost(num) { //O(n^2) 2 | // Write your code here 3 | let sum = 0; 4 | while (num.length > 1) { 5 | //getiing min val1 and removing it from array 6 | let num1 = Math.min(...num) 7 | let idx1 = num.indexOf(num1) 8 | num.splice(idx1, 1) 9 | 10 | //getiing min val2 and removing it from array 11 | let num2 = Math.min(...num) 12 | let idx2 = num.indexOf(num2) 13 | num.splice(idx2, 1) 14 | 15 | //adding to sum and push new val 16 | sum += num1 + num2 17 | num.push(num1 + num2) 18 | } 19 | return sum 20 | 21 | } 22 | -------------------------------------------------------------------------------- /12-7/co-prime.js: -------------------------------------------------------------------------------- 1 | function coprimeCount(A) { 2 | let res = [] 3 | A.forEach(val => { 4 | res.push(helper(val)) 5 | }) 6 | return res 7 | } 8 | 9 | function helper(val) { 10 | let res = val 11 | let factor = 2 12 | while (factor * factor <= val) { 13 | if (val % factor === 0) { 14 | while (val % factor === 0) { 15 | val /= factor 16 | } 17 | res -= (res / factor) 18 | } 19 | factor++ 20 | } 21 | if (val >= 2) { 22 | res -= (res / val) 23 | } 24 | return res 25 | 26 | } 27 | 28 | 29 | //explanation link https: //cp-algorithms.com/algebra/phi-function.html -------------------------------------------------------------------------------- /12-7/countingClosedPaths.js: -------------------------------------------------------------------------------- 1 | function closedPaths(number) { 2 | // Write your code here 3 | let sum = 0 4 | let paths = { '0': 1, '4': 1, '6': 1, '9': 1, '8': 2 } 5 | number = number.toString().split('') 6 | number.forEach(num => { 7 | if (paths[num]) { 8 | sum += parseInt(paths[num]) 9 | } 10 | }) 11 | return sum 12 | } 13 | -------------------------------------------------------------------------------- /12-7/getUmbrellas.js: -------------------------------------------------------------------------------- 1 | function getUmbrellas(requirement, sizes) { 2 | // Write your code here 3 | //[2,4] 4 | //0. 1. 2. 3. 4. 5 | //[0,inf,1, inf, 1] 6 | const coveredDPA = new Array(requirement + 1).fill(Infinity); 7 | coveredDPA[0] = 0; 8 | for (let size of sizes) { 9 | for (let i = 0; i < coveredDPA.length; i++) { 10 | if (size <= i) { 11 | coveredDPA[i] = Math.min(coveredDPA[i], coveredDPA[i - size] + 1) 12 | } 13 | } 14 | } 15 | if (coveredDPA[requirement] !== Infinity) { 16 | return coveredDPA[requirement] 17 | } else { 18 | return -1 19 | } 20 | } -------------------------------------------------------------------------------- /4-12/countBinarySubstrings.js: -------------------------------------------------------------------------------- 1 | function getSubstringCount(s) { 2 | 3 | let prev = 0; 4 | let curr = 1; 5 | let ans = 0; 6 | 7 | for (let i = 1; i < s.length; i++) { 8 | const prevBit = s[i - 1]; 9 | const currBit = s[i]; 10 | 11 | if (prevBit != currBit) { 12 | ans += Math.min(curr, prev); 13 | prev = curr; 14 | curr = 0; 15 | } 16 | curr++; 17 | } 18 | 19 | return ans + Math.min(curr, prev); 20 | } -------------------------------------------------------------------------------- /4-12/cuttingMetalSurplus.js: -------------------------------------------------------------------------------- 1 | function maxProfit(costPerCut, salePrice, lengths) { 2 | // Write your code here 3 | let maxProfit = 0 4 | let max = Math.max(...lengths) 5 | let test; 6 | for (let i = 1; i <= max; i++) { 7 | test = helper(i, costPerCut, salePrice, lengths) 8 | maxProfit = Math.max(maxProfit, test) 9 | } 10 | return maxProfit 11 | } 12 | 13 | 14 | function helper(currLength, costPerCut, salePrice, lengths) { 15 | let totalUniformRods = 0; 16 | let totalCuts = 0 17 | for (let i = 0; i < lengths.length; i++) { //[20, 59, 110] - currLength =2 18 | let currRod = lengths[i]; //20 19 | if (currLength > currRod) continue 20 | let tempCut = 0 21 | let tempTotalUniformRods = 0 22 | 23 | if (currRod % currLength === 0) { 24 | tempCut = Math.floor(currRod / currLength) - 1 25 | 26 | } else { 27 | tempCut = Math.floor(currRod / currLength) 28 | } 29 | tempTotalUniformRods = Math.floor(currRod / currLength) 30 | if (tempTotalUniformRods * currLength * salePrice - tempCut * costPerCut > 0) { 31 | totalCuts += tempCut 32 | totalUniformRods += tempTotalUniformRods 33 | 34 | } 35 | } 36 | return totalUniformRods * currLength * salePrice - totalCuts * costPerCut 37 | } 38 | -------------------------------------------------------------------------------- /4-12/jumptheflag.js: -------------------------------------------------------------------------------- 1 | function jumps(flagHeight, bigJump) { 2 | debugger 3 | let totalJumps = 0; 4 | if (flagHeight >= bigJump) { 5 | totalJumps += Math.floor(flagHeight / bigJump) 6 | totalJumps += flagHeight % bigJump 7 | return totalJumps 8 | } 9 | return flagHeight 10 | } -------------------------------------------------------------------------------- /4-12/rollTheString.js: -------------------------------------------------------------------------------- 1 | function rollTheString(s, roll) { 2 | 3 | const rollTimes = new Array(s.length).fill(0); //[1,1,1] 4 | for (const r of roll) { 5 | rollTimes[r - 1] += 1; 6 | } 7 | for (let i = rollTimes.length - 2; i >= 0; i--) { 8 | rollTimes[i] += rollTimes[i + 1]; 9 | } 10 | 11 | let rolledString = ''; 12 | for (let i = 0; i < rollTimes.length; i++) { 13 | const times = rollTimes[i]; 14 | const alphabetIndex = s[i].charCodeAt() - 97; 15 | const newAlphabetIndex = (alphabetIndex + times) % 26; 16 | rolledString += String.fromCharCode(newAlphabetIndex + 97); 17 | } 18 | 19 | return rolledString; 20 | } 21 | --------------------------------------------------------------------------------