Posts

Showing posts with the label Counting

Count Pairs That Form a Complete Day II - Counting Modulo Values [JS]

Description   Solution: Counting Modulo Values Keep a running count of occurances of each  hour % 24 . For each hour, we need to find the other modulo value needed to make up a multiple of  24 :  24 - (hour % 24) Return the total sum of  count[(24 - (hour % 24)) % 24] . n = length of hours Time Complexity:  O(n) Space Complexity:  O(24)  =  O(1) var countCompleteDayPairs = function ( hours ) { let count = Array ( 24 ).fill( 0 ), pairs = 0 ; for ( let hour of hours) { pairs += count[( 24 - (hour % 24 )) % 24 ]; count[hour % 24 ]++; } return pairs; };

Minimum Operations to Write the Letter Y on a Grid - Counting & Enumeration [JS]

Description   Solution: Counting & Enumeration Count the occurances of each value in the grid, inside the Y and outside the Y. Enumerate through all combinations of the values inside the Y and outside the Y. For a combination of values  (i, j) , calculate the number of operations to change all values inside the Y to  i , and all values outside the Y to  j . Record and return the minimum operations out of all combinations. How to check if  (row, col)  is inside the Y: Separate the checks into three segments, the left part ( \ ), the right part ( / ), and the middle part ( | ). The left part ( \ ):  row <= floor(n / 2) and row === col The right part ( / ):  row <= floor(n / 2) and row + col === n - 1 The middle part ( | ):  row >= floor(n / 2) and col === floor(n / 2) Time Complexity:  O(n^2) Space Complexity:  O(1) var minimumOperationsToWriteY = function ( grid ) { let countY = Array ( 3 ).fill( 0 ); let countOut...

Minimum Number of Pushes to Type Word II - Counting & Greedy [JS]

Description   Solution: Counting & Greedy It is optimal to assign characters with the most occurances to the front positions on the keys. Count the occurances of each character. Collect the counts and sort them in desc order. Greedily assign characters with the most occurances to the front positions. Assign the first eight counts to the first positions in the eight keys. Assign the second eight counts to the second positions in the eight keys. ... and so on. Time Complexity:  O(n) Space Complexity:  O(1) var minimumPushes = function ( word ) { let count = Array ( 26 ).fill( 0 ), n = word.length; for ( let i = 0 ; i < n; i++) { count[word.charCodeAt(i) - 97 ]++; } let counts = []; for ( let i = 0 ; i < 26 ; i++) { if (count[i] > 0 ) counts.push(count[i]); } counts.sort( ( a, b ) => b - a); let ans = 0 ; for ( let i = 0 ; i < counts.length; i++) { let position = Math .floor(i / 8 ) + 1 ; ans += position * cou...