|

A StoneWall Solution in C++

StoneWall is an interesting problem that requires some brain cycles yet not too complex. It is good software engineer interview question.

Here is a C++ solution whose complexity is O(N).

#include <stack>

int solution(std::vector<int> &H) {
    int stones = 0;
    std::stack<int> heights;

    for (auto h: H) {
        while (!heights.empty() && h < heights.top()) {
            heights.pop();
        }
        if (heights.empty() || h > heights.top()) {
            heights.push(h);
            ++stones;
        }
    }
    return stones;
}

Analysis of the StoneWall problem

The key insight here (from the example and figure too) is that when a new wall of height h is added on the most right side, if it is the same height as the right most one among those walls on its left that are not taller than h, no need to use an additional stone for the wall. The stone for the wall of the same height on its left can be re-used for this wall.

Step by step analysis of the code

The data structure
During the walls are added one by one to the right, the taller ones than the latest one on the left one of the latest one need not to be checked again later. But the same height or shorter ones on the left should be considered still. So, this pattern is like “first in latest out”, right? A stack is suitable.

The algorithm
Now we have the key insight and the data structure of a heights stack, we can process the walls one by one.

For each wall, first remove/pop the walls on its left that is higher until the stack is empty or the wall is not higher than it. Then, compare the right most one (highest one) if there is at least one wall left in the stack. If the height is the same, continue to next wall. If the height of the highest one in the stack (the top) is smaller, add the new wall to the stack and count one more stone.

Complexity analysis

The for loop goes through each element once -> O(N) times where N is the size of the input H. Now let’s check the complexity for each element.

For each element, there is a while loop inside. But, for each element, it will be pushed at most once to the stack and popped at most once from the stack.

So overall, the complexity is O(N).

Similar Posts

  • How to improve ssh/scp performance on Linux?

    ssh/scp are convenient and handy tools on Linux. Is is possible to further improve its speed/performance? Please check this post for how to improve ssh/scp performance: https://www.systutorials.com/5450/improving-sshscp-performance-by-choosing-ciphers/ Read more: Improving ssh/scp Performance by Choosing Suitable Ciphers Open Source and Portable SSH, SCP, SFTP and VNC Clients for Windows to Remote Control Linux How to improve…

  • How to merge multiple PDF files to a PDF on Linux?

    convert seems works not very well when merging PDFs. The quality is low. Any other better methods to merge multiple PDF files to a single PDF on Linux? ghostscript works the best for me on merging PDFs: gs -q -sPAPERSIZE=letter -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile=out.pdf in1.pdf in2.pdf in3.pdf merges in{1..3}.pdf to out.pdf. Read more: How…

  • Micosoft招聘部分算法题

    Micosoft招聘部分算法题 1.链表和数组的区别在哪里? 2.编写实现链表排序的一种算法。说明为什么你会选择用这样的方法? 3.编写实现数组排序的一种算法。说明为什么你会选择用这样的方法? 4.请编写能直接实现strstr()函数功能的代码。 5.编写反转字符串的程序,要求优化速度、优化空间。 6.在链表里如何发现循环链接? 7.给出洗牌的一个算法,并将洗好的牌存储在一个整形数组里。 8.写一个函数,检查字符是否是整数,如果是,返回其整数值。(或者:怎样只用4行代码编写出一个从字符串到长整形的函数?) 9.给出一个函数来输出一个字符串的所有排列。 10.请编写实现malloc()内存分配函数功能一样的代码。 11.给出一个函数来复制两个字符串A和B。字符串A的后几个字节和字符串B的前几个字节重叠。 12.怎样编写一个程序,把一个有序整数数组放到二叉树中? 13.怎样从顶部开始逐层打印二叉树结点数据?请编程。 14.怎样把一个链表掉个顺序(也就是反序,注意链表的边界条件并考虑空链表)? 来源:·日月光华 bbs.fudan.edu.cn Read more: How to Connect to MySQL in JSP OCaml Learning Materials Inline Assembly with GCC on Linux Online Tutorials for Linux Beginners How to Run a Command Upon Files or Directories Changes on Linux Filter Salutation in…

  • How to force ssh client to authenticate using password on Linux?

    ssh client can use many authentication methods like password, keys. On a server, I set password-less log in with private/public key. Now, I want to try whether the new password is set correctly by log on using ssh. By default, the key-based authentication method is used again. How to force ssh client to authenticate using…

  • How to get the hostname of the node in C++?

    In C++, how to get the hostname of the node? In C++, the C way works too. However, with Boost, you can use the boost::asio::ip::host_name() function to get the hostname as a std::string: namespace boost { namespace asio { namespace ip { /// Get the current host name. BOOST_ASIO_DECL std::string host_name(); … More at http://www.boost.org/doc/libs/1_63_0/boost/asio/ip/host_name.hpp…

Leave a Reply

Your email address will not be published. Required fields are marked *