We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
C++ solution, using a stack implementation, it can be done using a vector or a deque.
structStack{unique_ptr<int[]>m_stack;intm_tos;size_tm_size;Stack():m_stack(nullptr),m_tos(0),m_size(0){}Stack(size_tsize):m_stack(newint[size]),m_tos(0),m_size(size){}Stack&operator=(Stack&o){m_stack.swap(o.m_stack);m_tos=o.m_tos;m_size=o.m_size;return*this;}boolpush(constint&n){if(m_tos==m_size){returnfalse;}m_stack[m_tos++]=n;returntrue;}boolpop(int&n){if(m_tos==0){returnfalse;}n=m_stack[--m_tos];returntrue;}};boolis_prime(intn){if(n%2==0||n%3==0||n%5==0||n%7==0){returnfalse;}intdiv{static_cast<int>(sqrt(n)+1)};while(div>7){if(n%div==0){returnfalse;}--div;}returntrue;}intnext_prime(intn){intp{n+1};if(n<2){return2;}if(n<3){return3;}if(n<5){return5;}if(n<7){return7;}while(!is_prime(p)){++p;}returnp;}vector<int>waiter(vector<int>number,intq){vector<int>ans{};size_tn{number.size()};Stacka{n};Stackb{n};ints{};intp{};// push plates on A0for(constauto&n:number){a.push(n);}for(inti{};i<q;++i){Stackc{n};p=next_prime(p);while(a.pop(s)){if(s%p==0){b.push(s);// Bi}else{c.push(s);// temp stack (Ai)}}a=c;// Ai// move Bi to answhile(b.pop(s)){ans.push_back(s);}}while(a.pop(s)){ans.push_back(s);}returnans;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Waiter
You are viewing a single comment's thread. Return to all comments →
C++ solution, using a stack implementation, it can be done using a vector or a deque.