{"id":27390,"date":"2018-02-02T21:02:39","date_gmt":"2018-02-02T15:32:39","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27390"},"modified":"2018-02-02T21:02:39","modified_gmt":"2018-02-02T15:32:39","slug":"efficiently-implement-k-stacks-single-array","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/efficiently-implement-k-stacks-single-array\/","title":{"rendered":"How to efficiently implement k stacks in a single array"},"content":{"rendered":"<p>We have discussed space efficient implementation of 2 stacks in a single array. <span id=\"more-130897\"><\/span>In this post, a general solution for k stacks is discussed. Following is the detailed problem statement.<\/p>\n<p><em>Create a data structure kStacks that represents k stacks. Implementation of kStacks should use only one array, i.e., k stacks should use the same array for storing elements. Following functions must be supported by kStacks.<\/em><\/p>\n<p><em>push(int x, int sn) \u2013&gt; pushes x to stack number \u2018sn\u2019 where sn is from 0 to k-1<br \/>\npop(int sn) \u2013&gt; pops an element from stack number \u2018sn\u2019 where sn is from 0 to k-1<\/em><\/p>\n<p><strong>Method 1 (Divide the array in slots of size n\/k) <\/strong><br \/>\nA simple way to implement k stacks is to divide the array in k slots of size n\/k each, and fix the slots for different stacks, i.e., use arr[0] to arr[n\/k-1] for first stack, and arr[n\/k] to arr[2n\/k-1] for stack2 where arr[] is the array to be used to implement two stacks and size of array be n.<\/p>\n<p>The problem with this method is inefficient use of array space. A stack push operation may result in stack overflow even if there is space available in arr[]. For example, say the k is 2 and array size (n) is 6 and we push 3 elements to first and do not push anything to second second stack. When we push 4th element to first, there will be overflow even if we have space for 3 more elements in array.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Method 2 (A space efficient implementation)<\/strong><br \/>\nThe idea is to use two extra arrays for efficient implementation of k stacks in an array. This may not make much sense for integer stacks, but stack items can be large for example stacks of employees, students, etc where every item is of hundreds of bytes. For such large stacks, the extra space used is comparatively very less as we use two <em>integer <\/em>arrays as extra space.<\/p>\n<p>Following are the two extra arrays are used:<br \/>\n<strong><em>1) top[]:<\/em> <\/strong>This is of size k and stores indexes of top elements in all stacks.<br \/>\n<strong><em>2) next[]:<\/em><\/strong> This is of size n and stores indexes of next item for the items in array arr[]. Here arr[] is actual array that stores k stacks.<br \/>\nTogether with k stacks, a stack of free slots in arr[] is also maintained. The top of this stack is stored in a variable \u2018free\u2019.<\/p>\n<p>All entries in top[] are initialized as -1 to indicate that all stacks are empty. All entries next[i] are initialized as i+1 because all slots are free initially and pointing to next slot. Top of free stack, \u2018free\u2019 is initialized as 0.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>Following is C++ implementation of the above idea.<\/p>\n<p><strong>C++ Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">\/\/ A C++ program to demonstrate implementation of k stacks in a single <br\/>\/\/ array in time and space efficient way<br\/>#include&lt;iostream&gt;<br\/>#include&lt;climits&gt;<br\/>using namespace std;<br\/> <br\/>\/\/ A C++ class to represent k stacks in a single array of size n<br\/>class kStacks<br\/>{<br\/>    int *arr;   \/\/ Array of size n to store actual content to be stored in stacks<br\/>    int *top;   \/\/ Array of size k to store indexes of top elements of stacks<br\/>    int *next;  \/\/ Array of size n to store next entry in all stacks<br\/>                \/\/ and free list<br\/>    int n, k;<br\/>    int free; \/\/ To store beginning index of free list<br\/>public:<br\/>    \/\/constructor to create k stacks in an array of size n<br\/>    kStacks(int k, int n);<br\/> <br\/>    \/\/ A utility function to check if there is space available<br\/>    bool isFull()   {  return (free == -1);  }<br\/> <br\/>    \/\/ To push an item in stack number &#039;sn&#039; where sn is from 0 to k-1<br\/>    void push(int item, int sn);<br\/> <br\/>    \/\/ To pop an from stack number &#039;sn&#039; where sn is from 0 to k-1<br\/>    int pop(int sn);<br\/> <br\/>    \/\/ To check whether stack number &#039;sn&#039; is empty or not<br\/>    bool isEmpty(int sn)  {  return (top[sn] == -1); }<br\/>};<br\/> <br\/>\/\/constructor to create k stacks in an array of size n<br\/>kStacks::kStacks(int k1, int n1)<br\/>{<br\/>    \/\/ Initialize n and k, and allocate memory for all arrays<br\/>    k = k1, n = n1;<br\/>    arr = new int[n];<br\/>    top = new int[k];<br\/>    next = new int[n];<br\/> <br\/>    \/\/ Initialize all stacks as empty<br\/>    for (int i = 0; i &lt; k; i++)<br\/>        top[i] = -1;<br\/> <br\/>    \/\/ Initialize all spaces as free<br\/>    free = 0;<br\/>    for (int i=0; i&lt;n-1; i++)<br\/>        next[i] = i+1;<br\/>    next[n-1] = -1;  \/\/ -1 is used to indicate end of free list<br\/>}<br\/> <br\/>\/\/ To push an item in stack number &#039;sn&#039; where sn is from 0 to k-1<br\/>void kStacks::push(int item, int sn)<br\/>{<br\/>    \/\/ Overflow check<br\/>    if (isFull())<br\/>    {<br\/>        cout &lt;&lt; &quot;\\nStack Overflow\\n&quot;;<br\/>        return;<br\/>    }<br\/> <br\/>    int i = free;      \/\/ Store index of first free slot<br\/> <br\/>    \/\/ Update index of free slot to index of next slot in free list<br\/>    free = next[i];<br\/> <br\/>    \/\/ Update next of top and then top for stack number &#039;sn&#039;<br\/>    next[i] = top[sn];<br\/>    top[sn] = i;<br\/> <br\/>    \/\/ Put the item in array<br\/>    arr[i] = item;<br\/>}<br\/> <br\/>\/\/ To pop an from stack number &#039;sn&#039; where sn is from 0 to k-1<br\/>int kStacks::pop(int sn)<br\/>{<br\/>    \/\/ Underflow check<br\/>    if (isEmpty(sn))<br\/>    {<br\/>         cout &lt;&lt; &quot;\\nStack Underflow\\n&quot;;<br\/>         return INT_MAX;<br\/>    }<br\/> <br\/> <br\/>    \/\/ Find index of top item in stack number &#039;sn&#039;<br\/>    int i = top[sn];<br\/> <br\/>    top[sn] = next[i];  \/\/ Change top to store next of previous top<br\/> <br\/>    \/\/ Attach the previous top to the beginning of free list<br\/>    next[i] = free;<br\/>    free = i;<br\/> <br\/>    \/\/ Return the previous top item<br\/>    return arr[i];<br\/>}<br\/> <br\/>\/* Driver program to test twStacks class *\/<br\/>int main()<br\/>{<br\/>    \/\/ Let us create 3 stacks in an array of size 10<br\/>    int k = 3, n = 10;<br\/>    kStacks ks(k, n);<br\/> <br\/>    \/\/ Let us put some items in stack number 2<br\/>    ks.push(15, 2);<br\/>    ks.push(45, 2);<br\/> <br\/>    \/\/ Let us put some items in stack number 1<br\/>    ks.push(17, 1);<br\/>    ks.push(49, 1);<br\/>    ks.push(39, 1);<br\/> <br\/>    \/\/ Let us put some items in stack number 0<br\/>    ks.push(11, 0);<br\/>    ks.push(9, 0);<br\/>    ks.push(7, 0);<br\/> <br\/>    cout &lt;&lt; &quot;Popped element from stack 2 is &quot; &lt;&lt; ks.pop(2) &lt;&lt; endl;<br\/>    cout &lt;&lt; &quot;Popped element from stack 1 is &quot; &lt;&lt; ks.pop(1) &lt;&lt; endl;<br\/>    cout &lt;&lt; &quot;Popped element from stack 0 is &quot; &lt;&lt; ks.pop(0) &lt;&lt; endl;<br\/> <br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>Popped element from stack 2 is 45\r\nPopped element from stack 1 is 39\r\nPopped element from stack 0 is 7<\/pre>\n<p>Time complexities of operations push() and pop() is O(1).<\/p>\n<p>The best part of above implementation is, if there is a slot available in stack, then an item can be pushed in any of the stacks, i.e., no wastage of space.<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>How to efficiently implement k stacks in a single array &#8211; Stack &#8211; We have discussed space efficient implementation of 2 stacks in a single array. <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[73012,79607],"tags":[81530,81531,81533,81534,81532,81535,80441,80440],"class_list":["post-27390","post","type-post","status-publish","format-standard","hentry","category-data-structures","category-stack","tag-implement-3-stacks-in-a-single-array","tag-implement-k-stacks-in-a-single-array-java","tag-implement-multiple-queue-in-single-dimensional-array","tag-implement-multiple-stacks-in-a-single-dimensional-array","tag-implement-two-stacks-using-one-array-in-c","tag-multiple-queue-using-single-array","tag-multiple-stack-in-data-structure","tag-multiple-stack-using-array-in-c"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27390","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=27390"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27390\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27390"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27390"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27390"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}