Programmer interview questions 100 (02)-design a stack containing min Functions

Source: Internet
Author: User

Http://zhedahht.blog.163.com/blog/static/25411174200712895228171/

Question: To define the stack data structure, add a min function to obtain the minimum element of the stack. The time complexity of the min, push, and pop functions is O (1 ).

Analysis: this is an interview question from Google last year.

When I see this question, the first reaction is to sort all reverse elements in the stack every time a new element is pushed. In this way, the top element of the stack will be the smallest element. However, the data structure designed in this way is no longer a stack because it cannot guarantee that the elements pushed to the stack are first-in-first-out.

Add a member variable to the stack to store the smallest element (or the location of the smallest element ). Each time a new element is pushed to the stack, if the element is smaller than the current minimum element, the minimum element is updated.

At first glance, this is a good idea. But if you think about it, there is an important question: if the current minimum element is pop out, how can we get the next minimum element?

Therefore, it is not enough to add only one member variable to store the smallest element (or the location of the smallest element. We need an auxiliary stack. Each time a new element is pushed, the smallest element (or the position of the smallest element) is also pushed. Considering that the type of the stack element may be a complex data structure, using the location of the smallest element can reduce space consumption) push to the auxiliary stack; each time an element pops out of the stack, pop auxiliary stack at the same time.

During the push operation, compare the value D with the top element x of the stack of the secondary stack. If D <X, push D to the secondary stack, if D> = x, push X to the auxiliary stack. Two stacks, including the data stack and the secondary stack, will pop up one element during pop.
If you want to save space, you can compare the data between the inbound and outbound stacks, that is, only the elements that need to be added to the stack are smaller or equal to the elements at the top of the secondary stack. Otherwise, the stack is not included; when the stack is output, the stack element and the top element of the secondary Stack are determined. If they are equal, the stack is output. Otherwise, no operation is performed.

Reference code:

#include <deque>#include <assert.h>template <typename T> class CStackWithMin{public:      CStackWithMin(void) {}      virtual ~CStackWithMin(void) {}      T& top(void);      const T& top(void) const;      void push(const T& value);      void pop(void);      const T& min(void) const;private:     T> m_data;               // the elements of stack     size_t> m_minIndex;      // the indices of minimum elements};// get the last element of mutable stacktemplate <typename T> T& CStackWithMin<T>::top(){      return m_data.back();}// get the last element of non-mutable stacktemplate <typename T> const T& CStackWithMin<T>::top() const{      return m_data.back();}// insert an elment at the end of stacktemplate <typename T> void CStackWithMin<T>::push(const T& value){      // append the data into the end of m_data      m_data.push_back(value);      // set the index of minimum elment in m_data at the end of m_minIndex      if(m_minIndex.size() == 0)            m_minIndex.push_back(0);      else      {            if(value < m_data[m_minIndex.back()])                  m_minIndex.push_back(m_data.size() - 1);            else                  m_minIndex.push_back(m_minIndex.back());      }}// erease the element at the end of stacktemplate <typename T> void CStackWithMin<T>::pop(){      // pop m_data      m_data.pop_back();      // pop m_minIndex      m_minIndex.pop_back();}// get the minimum element of stacktemplate <typename T> const T& CStackWithMin<T>::min() const{      assert(m_data.size() > 0);      assert(m_minIndex.size() > 0);      return m_data[m_minIndex.back()];}

The following is an example of how to run the above Code:

Step: data stack auxiliary stack minimum value
1. Push 3 3 0 3
2. Push 4 3, 4, 0, 0 3
3. Push 2 3, 4, 2, 0, 2 2
4. Push 1 3,4
5. POP 3, 4, 2, 0, 2 2
6. POP 3, 4, 0 3
7. Push 0 3, 4, 0 0, 0, 2 0

Discussion: if the idea is correct, writing the above Code is not very difficult. However, if you can pay attention to some details, you will undoubtedly be able to score points during the interview. For example, I did the following work in the above Code:

· Use a template class. If the element type of others is only int, the template will give the interviewer a good impression;

· Two versions of top functions. In many classes, you must provide access functions for members of the const and non-const versions;

· Assert in the min function. Every software company requires programmers to write code securely;

· Add comments. Comments not only improve the readability of the code, but also increase the amount of code. Why not?

In short, if the time permits during the interview, try to write the code beautifully. Maybe a few highlights in the Code will make it easy for you to get your favorite offer.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.