Imagine a futuristic city where people can only move between buildings by jumping from one to another, but there's a catch - you can only jump to a taller building that's positioned to your right!
You're given an array heights where heights[i] represents the height of the i-th building. A person in building i can move to building j if and only if:
i < j(building j is to the right)heights[i] < heights[j](building j is taller)
You have multiple queries where Alice starts at building a[i] and Bob starts at building b[i]. For each query, find the leftmost building where both Alice and Bob can meet. If they can't meet anywhere, return -1.
The key challenge: Both Alice and Bob must be able to reach the same building following the jumping rules!
Input & Output
Visualization
Time & Space Complexity
For each of m queries, we potentially check all n buildings
Only using constant extra space for variables
Constraints
- 1 โค heights.length โค 5 ร 104
- 1 โค heights[i] โค 109
- 1 โค queries.length โค 5 ร 104
- queries[i] = [ai, bi]
- 0 โค ai, bi โค heights.length - 1