{"id":3705,"date":"2018-08-26T09:14:01","date_gmt":"2018-08-26T16:14:01","guid":{"rendered":"https:\/\/zxi.mytechroad.com\/blog\/?p=3705"},"modified":"2018-08-30T09:30:44","modified_gmt":"2018-08-30T16:30:44","slug":"leetcode-895-maximum-frequency-stack","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/desgin\/leetcode-895-maximum-frequency-stack\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 895. Maximum Frequency Stack"},"content":{"rendered":"<p><iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 895. Maximum Frequency Stack - \u5237\u9898\u627e\u5de5\u4f5c EP220\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/IkrGghj6_fk?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<h1><strong>Problem<\/strong><\/h1>\n<p>Implement\u00a0<code>FreqStack<\/code>, a class which simulates the operation of a stack-like data structure.<\/p>\n<p><code>FreqStack<\/code>\u00a0has two functions:<\/p>\n<ul>\n<li><code>push(int x)<\/code>, which pushes an integer\u00a0<code>x<\/code>\u00a0onto the stack.<\/li>\n<li><code>pop()<\/code>, which\u00a0<strong>removes<\/strong>\u00a0and returns the most frequent element in the stack.\n<ul>\n<li>If there is a tie for most frequent element, the element closest to the top of the stack is removed and returned.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p><strong>Example 1:<\/strong><\/p>\n<pre class=\"crayon:false \"><strong>Input: <\/strong>\r\n<span id=\"example-input-1-1\">[\"FreqStack\",\"push\",\"push\",\"push\",\"push\",\"push\",\"push\",\"pop\",\"pop\",\"pop\",\"pop\"]<\/span>,\r\n<span id=\"example-input-1-2\">[[],[5],[7],[5],[7],[4],[5],[],[],[],[]]<\/span>\r\n<strong>Output: <\/strong><span id=\"example-output-1\">[null,null,null,null,null,null,null,5,7,5,4]<\/span>\r\n<strong>Explanation<\/strong>:\r\nAfter making six .push operations, the stack is [5,7,5,7,4,5] from bottom to top.  Then:\r\n\r\npop() -&gt; returns 5, as 5 is the most frequent.\r\nThe stack becomes [5,7,5,7,4].\r\n\r\npop() -&gt; returns 7, as 5 and 7 is the most frequent, but 7 is closest to the top.\r\nThe stack becomes [5,7,5,4].\r\n\r\npop() -&gt; returns 5.\r\nThe stack becomes [5,7,4].\r\n\r\npop() -&gt; returns 4.\r\nThe stack becomes [5,7].\r\n<\/pre>\n<p><strong>Note:<\/strong><\/p>\n<ul>\n<li>Calls to\u00a0<code>FreqStack.push(int x)<\/code>\u00a0will be such that\u00a0<code>0 &lt;= x &lt;= 10^9<\/code>.<\/li>\n<li>It is guaranteed that\u00a0<code>FreqStack.pop()<\/code>\u00a0won&#8217;t be called if the stack has zero elements.<\/li>\n<li>The total number of\u00a0<code>FreqStack.push<\/code>\u00a0calls will not exceed\u00a0<code>10000<\/code>\u00a0in a single test case.<\/li>\n<li>The total number of\u00a0<code>FreqStack.pop<\/code>\u00a0calls will not exceed\u00a0<code>10000<\/code>\u00a0in a single test case.<\/li>\n<li>The total number of\u00a0<code>FreqStack.push<\/code>\u00a0and\u00a0<code>FreqStack.pop<\/code>\u00a0calls will not exceed\u00a0<code>150000<\/code>\u00a0across all test cases.<\/li>\n<\/ul>\n<p><ins class=\"adsbygoogle\" style=\"display: block; text-align: center;\" data-ad-layout=\"in-article\" data-ad-format=\"fluid\" data-ad-client=\"ca-pub-2404451723245401\" data-ad-slot=\"7983117522\">\u00a0<\/ins><\/p>\n<h1><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-3710\" src=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2018\/08\/895-ep220.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2018\/08\/895-ep220.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2018\/08\/895-ep220-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2018\/08\/895-ep220-768x432.png 768w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/h1>\n<h1><strong>Solution 1: Buckets<\/strong><\/h1>\n<p>We have n\u00a0 stacks. The i-th stack has the of elements with freq i when pushed.<\/p>\n<p>We keep tracking the freq of each element.<\/p>\n<p>push(x): stacks[++freq(x)].push(x)\u00a0 # inc x&#8217;s freq and push it onto freq-th stack<\/p>\n<p>pop(): x = stacks[max_freq].pop(), &#8211;freq(x); # pop element x from the max_freq stack and dec it&#8217;s freq.<\/p>\n<p>Time complexity: O(1) push \/ pop<\/p>\n<p>Space complexity: O(n)<\/p>\n<div class=\"responsive-tabs\">\n<h2 class=\"tabtitle\">C++<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:c++ decode:true \">\/\/ Author: Huahua\r\n\/\/ Running time: 144 ms\r\nclass FreqStack {\r\npublic:\r\n  FreqStack() {}\r\n\r\n  void push(int x) {\r\n    auto it = freq_.find(x);\r\n    if (it == freq_.end())\r\n      it = freq_.emplace(x, 0).first;    \r\n    int freq = ++it-&gt;second;    \r\n    if (stacks_.size() &lt; freq) stacks_.push_back({});\r\n    stacks_[freq - 1].push(x);\r\n  }\r\n\r\n  int pop() {    \r\n    int x = stacks_.back().top();    \r\n    stacks_.back().pop();\r\n    if (stacks_.back().empty())\r\n      stacks_.pop_back();\r\n    auto it = freq_.find(x);\r\n    if (!(--it-&gt;second))\r\n      freq_.erase(it);\r\n    return x;\r\n  }\r\nprivate:  \r\n  vector&lt;stack&lt;int&gt;&gt; stacks_;\r\n  unordered_map&lt;int, int&gt; freq_;\r\n};<\/pre>\n<\/div><\/div>\n<h1>Solution2: Priority Queue<\/h1>\n<p>Use a max heap with key: (freq, seq), the max freq and closest to the top of stack element will be extracted first.<\/p>\n<p>Time complexity: O(logn)<\/p>\n<p>Space complexity: O(n)<\/p>\n<div class=\"responsive-tabs\">\n<h2 class=\"tabtitle\">C++<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:c++ decode:true\">\/\/ Author: Huahua\r\n\/\/ Running time: 132 ms\r\nclass FreqStack {\r\npublic:\r\n  FreqStack() {}\r\n\r\n  void push(int x) {    \r\n    int key = (++f_[x] &lt;&lt; 16) | (++seq_);\r\n    q_.emplace(key, x);\r\n  }\r\n\r\n  int pop() {\r\n    int x = q_.top().second; q_.pop();    \r\n    if (--f_[x] == 0)\r\n      f_.erase(x);\r\n    return x;\r\n  }\r\nprivate:\r\n  int seq_ = 0;\r\n  unordered_map&lt;int, int&gt; f_; \/\/ {x -&gt; freq}\r\n  priority_queue&lt;pair&lt;int, int&gt;&gt; q_; \/\/ {freq | seq_, x}\r\n};<\/pre>\n<\/div><\/div>\n<h1><strong>Related Problems<\/strong><\/h1>\n<ul>\n<li><a href=\"https:\/\/zxi.mytechroad.com\/blog\/hashtable\/leetcode-460-lfu-cache\/\">\u82b1\u82b1\u9171 LeetCode 460. LFU Cache<\/a><\/li>\n<li><a href=\"https:\/\/zxi.mytechroad.com\/blog\/hashtable\/leetcode-146-lru-cache\/\">\u82b1\u82b1\u9171 LeetCode 146. LRU Cache O(1)<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Problem Implement\u00a0FreqStack, a class which simulates the operation of a stack-like data structure. FreqStack\u00a0has two functions: push(int x), which pushes an integer\u00a0x\u00a0onto the stack. pop(),&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[340],"tags":[387,217,72,180],"class_list":["post-3705","post","type-post","status-publish","format-standard","hentry","category-desgin","tag-freq","tag-hard","tag-priority-queue","tag-stack","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/3705","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/comments?post=3705"}],"version-history":[{"count":9,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/3705\/revisions"}],"predecessor-version":[{"id":3755,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/3705\/revisions\/3755"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=3705"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=3705"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=3705"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}