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.
Jim and the Skyscrapers
Jim and the Skyscrapers
Sort by
recency
|
75 Discussions
|
Please Login in order to post a comment
O(n) proposal
basically each element is visited ~twice
Succint python solution using priority queue and dictionary. O(N) runtime. O(N) space.
Quite readable solution in Kotlin, with detailed explanation.
Problem
Given an array of
heights
of skyscrapers, you can fly from a skyscraperi
to a skyscrapersj != i
iffheights[i] == heights[j]
andheights[i] > heights[k]
for allk in [i + 1..j - 1]
.Find the number of direct flying paths from skyscraper
i
toj
, counting both casesi < j
andi > j
.Solution
We use a monotonic queue/stack, see
Idea
ni = heights[i]
:ni
remained on the stack, or the stack is empty.ni
, then we can fly from the corresponding preceding skyscrapers toi
so we increase the resulting path count by the count of occurrences ofni
stored on the stack. We then also increase the count of occurrences ofni
, because we just encountered another one.ni
with the initial occurrence count1
.(i, j)
we need to count both the forward path withi < j
and the backward path withi > j
.Runtime
The runtime is
O(n)
:ni
of the input array would be considered only a constant number of times:1
peek
operation on the stack.n
pushes (at most1
for each array element), and thus at mostn
removals.Kotlin implementation
my answer with O(n) time:
Here is my code with comments: