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
|
76 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
heightsof skyscrapers, you can fly from a skyscraperito a skyscrapersj != iiffheights[i] == heights[j]andheights[i] > heights[k]for allk in [i + 1..j - 1].Find the number of direct flying paths from skyscraper
itoj, counting both casesi < jandi > j.Solution
We use a monotonic queue/stack, see
Idea
ni = heights[i]:niremained on the stack, or the stack is empty.ni, then we can fly from the corresponding preceding skyscrapers toiso we increase the resulting path count by the count of occurrences ofnistored on the stack. We then also increase the count of occurrences ofni, because we just encountered another one.niwith the initial occurrence count1.(i, j)we need to count both the forward path withi < jand the backward path withi > j.Runtime
The runtime is
O(n):niof the input array would be considered only a constant number of times:1peekoperation on the stack.npushes (at most1for each array element), and thus at mostnremovals.Kotlin implementation
my answer with O(n) time: