LeetCode: Reduce Array Size to The Half Solution
Hash table, sort by occurences then greedily removeApproach
Steps:
- Build hash map with key-value pairs of element-occurence
- Sort the pairs by occurence
- Greedily remove from the largest occurence
Implementation
1/**2 * @param {number[]} arr3 * @return {number}4 */5var minSetSize = function (arr) {6 const n = arr.length78 const occurrences = arr.reduce(9 (acc, el) => acc.set(el, (acc.get(el) || 0) + 1),10 new Map()11 )1213 const pairsSortedByOccurencesDesc = [...occurrences.entries()].sort(14 ([_, occurrenceA], [__, occurrenceB]) => occurrenceA - occurrenceB15 )1617 let i = n18 let setRemovedLength = 01920 while (i > Math.floor(n / 2)) {21 i -= pairsSortedByOccurencesDesc.pop()[1]22 setRemovedLength++23 }2425 return setRemovedLength26}
References
Array.prototype.reduce() (MDN Web Docs)
Comments
Loading comments...
Tags
leetcode
hash table
sorting
greedy
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Maximum Length of Repeated Subarray
Memoized recursion, somewhat similar to "Longest common subsequence"
Previous Post
LeetCode: Kth Smallest Element in a Sorted Matrix
Flatten and sort