An O(n) solution involving a stack exists and although the solution is very concise, it is somewhat unintuitive and difficult to follow. It follows similar principle to the O(n²) solution, but we push elements to a stack if they are bigger than previous to deal with them later. As we move through the bars, we are looking for the end of an area box, which is marked when a bar (i) is smaller than that previous bar on the top of the stack. We stop to deal with that top stack bar, so pop it and call it’s index tp. We then go back to the stack (s) to find out the starting bound of the area box, which is marked by the next item in the stack, which is smaller than tp. We calculate the area = heights[tp] * (i – s.top() – 1); unless there is no item in the stack in which case area = heights * i; i.e. span all the way to the beginning.

]]>I have seen it implemented with a single array where you initialise it to frequencies of chars in t and then you decrement those frequencies as you come across them in the window. When you get to zero then that means you’ve got the required amount. Less than 0 and you have more than the required amount and in that case you don’t add to count. That’s a clever solution but I think my one is more intuitive and easier to follow.

]]>Here’s the source code for that initial solution:

https://gist.github.com/adamkorg/36adeab8156778d3852c37a57fb250aa

And here’s the source code for the simplified getline()/stringstream solution:

1) Overflow: I overcome this by checking against a limit for mid so that the square cannot exceed the integer limit. I noticed on leetcode that most solutions use a long variable to calculate the square, which on Unix systems (LP64) will work but not on Windows (LLP64).

2) Upper bound check: It might be possible that at our loop end condition, we haven’t checked the upper bound. So I check this out of the loop. ]]>