Skip to main content

3016.js

/** ------------------------------------------------------------------------------
*
* 3016. Minimum Number of Pushes to Type Word II
* Topics: Hash Table, Greedy
* https://leetcode.com/problems/minimum-number-of-pushes-to-type-word-ii/description/?envType=daily-question&envId=2024-08-06
*
------------------------------------------------------------------------------ */
/**
* @param {string} word
* @return {number}
*/
var minimumPushes1 = function (word) {
const keypad = new Set(word)

if (keypad.size < 9) {
return word.length
}

const map = new Map()
for (let i = 0; i < word.length; i++) {
map.set(word[i], (map.get(word[i]) || 0) + 1)
}

const array = Array.from(map.entries())

array.sort((a, b) => b[1] - a[1])

let answer = 0
let keypadTimes = 0

for (let i = 0; i < array.length; i++) {
if (i % 8 === 0) {
keypadTimes++
}
const [_, count] = array[i]
answer = answer + count * keypadTimes
}

return answer
}

/**
* 시간복잡도 Good
*/
var minimumPushes = function (word) {
let arr = new Array(26).fill(0)

for (let i = 0; i < word.length; i++) {
arr[word.charCodeAt(i) - "a".charCodeAt(0)]++
}

arr.sort((a, b) => b - a)
let keypadTimes = 0
let ans = 0

for (let i = 0; i < arr.length; i++) {
if (arr[i] == 0) break
ans += (1 + Math.floor(keypadTimes++ / 8)) * arr[i]
}
return ans
}

console.log(minimumPushes("aabbccddeeffgghhiiiiii"))