Talentd
FleetCode
Make and follow sheets.Sign in

Find Building Where Alice and Bob Can Meet solution and explanation

HardArrayBinary Indexed TreeBinary SearchHeap (Priority Queue)8 min read52.3% acceptanceUpdated 9 Apr 2026
Find Building Where Alice and Bob Can Meet - Leetcode 2940 - PythonNeetCodeIO · 29:43 · 13K viewsWatch on YouTube
9 more videos on this problem
  1. Find Building Where Alice and Bob Can Meet - Leetcode 2940 - PythonNeetCodeIO · 29:43 · 13K views
  2. Find Building Where Alice and Bob Can Meet | Segment Tree Concepts & Qns | Video 11 | Leetcode 2940codestorywithMIK · 37:09 · 12K views
  3. 2940. Find Building Where Alice and Bob Can Meet | Monotonic stack | Priority QueueAryan Mittal · 29:01 · 6K views
  4. Find Building Where Alice and Bob Can Meet | Segment Tree | Binary Search | Leetcode 2940Techdose · 43:31 · 5K views
  5. 2940. Find Building Where Alice and Bob Can Meet | Weekly Leetcode 372codingMohan · 25:25 · 2K views
  6. 2940. Find Building Where Alice and Bob Can Meet | Priority Queue | Contest 372Tech Courses · 25:11 · 2K views
  7. 2940. Find Building Where Alice and Bob Can Meet (Leetcode Hard)Programming Live with Larry · 1:14:16 · 586 views
  8. Find Building Where Alice and Bob Can Meet - LeetCode 2940 - PythonAlpha-Code · 30:37 · 513 views
  9. Daily Leetcode #1727: Dec 22, 2024 - 2940. Find Building Where Alice and Bob Can MeetProgramming Live with Larry · 22:11 · 496 views
  10. Find Building Where Alice and Bob Can Meet | LeetcodeEthos Typos · 21:43 · 366 views

The problem

You are given a 0-indexed array heights of positive integers, where heights[i] represents the height of the ith building.

If a person is in building i, they can move to any other building j if and only if i < j and heights[i] < heights[j].

You are also given another array queries where queries[i] = [ai, bi]. On the ith query, Alice is in building ai while Bob is in building bi.

Return an array ans where ans[i] is the index of the leftmost building where Alice and Bob can meet on the ith query. If Alice and Bob cannot move to a common building on query i, set ans[i] to -1.

Example 1:

Input: heights = [6,4,8,5,2,7], queries = [[0,1],[0,3],[2,4],[3,4],[2,2]]
Output: [2,5,-1,5,2]
Explanation: In the first query, Alice and Bob can move to building 2 since heights[0] < heights[2] and heights[1] < heights[2]. 
In the second query, Alice and Bob can move to building 5 since heights[0] < heights[5] and heights[3] < heights[5]. 
In the third query, Alice cannot meet Bob since Alice cannot move to any other building.
In the fourth query, Alice and Bob can move to building 5 since heights[3] < heights[5] and heights[4] < heights[5].
In the fifth query, Alice and Bob are already in the same building.  
For ans[i] != -1, It can be shown that ans[i] is the leftmost building where Alice and Bob can meet.
For ans[i] == -1, It can be shown that there is no building where Alice and Bob can meet.

Example 2:

Input: heights = [5,3,8,2,6,1,4,6], queries = [[0,7],[3,5],[5,2],[3,0],[1,6]]
Output: [7,6,-1,4,6]
Explanation: In the first query, Alice can directly move to Bob's building since heights[0] < heights[7].
In the second query, Alice and Bob can move to building 6 since heights[3] < heights[6] and heights[5] < heights[6].
In the third query, Alice cannot meet Bob since Bob cannot move to any other building.
In the fourth query, Alice and Bob can move to building 4 since heights[3] < heights[4] and heights[0] < heights[4].
In the fifth query, Alice can directly move to Bob's building since heights[1] < heights[6].
For ans[i] != -1, It can be shown that ans[i] is the leftmost building where Alice and Bob can meet.
For ans[i] == -1, It can be shown that there is no building where Alice and Bob can meet.

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

Approach overview

Problem Overview: You are given building heights and multiple queries. Each query contains two starting buildings for Alice and Bob. They can only move to the right and only to a building with a strictly greater height. The goal is to return the leftmost building index where both can meet, or -1 if no such building exists.

Approach 1: Next Greater Element Precomputation (O((n+q) log n) time, O(n log n) space)

The movement rule is identical to the classic next greater element pattern. From any building i, the next possible move is the first index to the right with a greater height. Compute this using a monotonic stack in O(n). This forms a directed chain of valid jumps.

For each query (a, b), normalize so a ≤ b. If heights[a] < heights[b], they can meet directly at b. Otherwise, Bob cannot move left, so the answer must be some building to the right of b with height greater than heights[a]. Using the precomputed next-greater links, build binary lifting jump pointers so you can quickly skip through the chain until you find the first building taller than heights[a]. Each query becomes a logarithmic search over the jump table.

This approach works well because the next-greater structure compresses all valid moves into a monotonic chain. Instead of scanning linearly, you jump across increasing heights using precomputed powers of two.

Approach 2: Binary Search on Preprocessed Data (O((n+q) log n) time, O(n) space)

Another strategy processes buildings while maintaining a decreasing stack of candidate indices. The stack represents buildings that could serve as the next taller building for future positions. As you scan from right to left, you remove shorter buildings and maintain a monotonic structure similar to the classic stack next-greater algorithm.

For each query where a ≤ b and heights[a] ≥ heights[b], the meeting building must be to the right of b and must exceed heights[a]. The candidate stack to the right of b is strictly increasing in height, so you can apply binary search to locate the first building whose height is greater than heights[a]. Preprocessing ensures the candidate list remains ordered, making each lookup logarithmic.

This method avoids jump pointers and instead relies on the monotonic property of the stack. Binary search quickly identifies the first valid meeting building.

Recommended for interviews: The monotonic stack preprocessing combined with logarithmic queries is typically expected. It demonstrates understanding of next greater element patterns and efficient query handling. Starting with the brute-force idea (scan to the right for every query) shows the intuition, but the optimized approach using stack-based preprocessing and binary search shows strong algorithmic maturity.

Approach 1: Precompute the Next Greater Element

This approach involves preprocessing the heights array to identify each building's nearest potential building with greater height. For each query, you can then quickly determine the first such building where both Alice and Bob can move. This significantly reduces unnecessary repeated calculations for multiple queries.

def findMeetBuilding(heights, queries):
    n = len(heights)
    next_greater = [n] * n
    stack = []

    for i in range(n-1, -1, -1):
        while stack and heights[stack[-1]] <= heights[i]:
            stack.pop()
        if stack:
            next_greater[i] = stack[-1]
        stack.append(i)

    ans = []
    for a, b in queries:
        meet = next_greater[a]
        while meet < n and meet <= b and next_greater[b] != meet:
            meet = next_greater[meet]
        ans.append(meet if meet < n and meet <= b else -1)

    return ans
import java.util.*;

class Solution {
    public int[] findMeetBuilding(int[] heights, int[][] queries) {
        int n = heights.length;
        int[] nextGreater = new int[n];
        Arrays.fill(nextGreater, n);
        Deque<Integer> stack = new ArrayDeque<>();

        for (int i = n - 1; i >= 0; --i) {
            while (!stack.isEmpty() && heights[stack.peek()] <= heights[i]) {
                stack.pop();
            }
            if (!stack.isEmpty()) {
                nextGreater[i] = stack.peek();
            }
            stack.push(i);
        }

        int[] ans = new int[queries.length];
        for (int i = 0; i < queries.length; ++i) {
            int a = queries[i][0], b = queries[i][1];
            int meet = nextGreater[a];
            while (meet < n && meet <= b && nextGreater[b] != meet)
                meet = nextGreater[meet];
            ans[i] = (meet < n && meet <= b) ? meet : -1;
        }
        return ans;
    }
}
#include <vector>
#include <stack>
using namespace std;

vector<int> findMeetBuilding(vector<int>& heights, vector<vector<int>>& queries) {
    int n = heights.size();
    vector<int> nextGreater(n, n);
    stack<int> s;
    for (int i = n - 1; i >= 0; --i) {
        while (!s.empty() && heights[s.top()] <= heights[i]) s.pop();
        if (!s.empty()) nextGreater[i] = s.top();
        s.push(i);
    }
    vector<int> ans;
    for (const auto& q : queries) {
        int a = q[0], b = q[1];
        int meet = nextGreater[a];
        while (meet < n && meet <= b && nextGreater[b] != meet) 
            meet = nextGreater[meet];
        ans.push_back((meet < n && meet <= b) ? meet : -1);
    }
    return ans;
}
function findMeetBuilding(heights, queries) {
    const n = heights.length;
    const nextGreater = Array(n).fill(n);
    const stack = [];

    for (let i = n - 1; i >= 0; i--) {
        while (stack.length && heights[stack[stack.length - 1]] <= heights[i]) {
            stack.pop();
        }
        if (stack.length) {
            nextGreater[i] = stack[stack.length - 1];
        }
        stack.push(i);
    }

    const ans = [];
    for (const [a, b] of queries) {
        let meet = nextGreater[a];
        while (meet < n && meet <= b && nextGreater[b] != meet) {
            meet = nextGreater[meet];
        }
        ans.push(meet < n && meet <= b ? meet : -1);
    }
    return ans;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int* findMeetBuilding(int* heights, int heightsSize, int** queries, int queriesRowSize, int* queriesColSize, int* returnSize) {
    *returnSize = queriesRowSize;
    int* ans = (int*)malloc(sizeof(int) * queriesRowSize);
    int* nextGreater = (int*)malloc(sizeof(int) * heightsSize);
    int* stack = (int*)malloc(sizeof(int) * heightsSize);
    int top = -1;

    for (int i = heightsSize - 1; i >= 0; i--) {
        while (top != -1 && heights[stack[top]] <= heights[i]) {
            top--;
        }
        nextGreater[i] = (top == -1) ? heightsSize : stack[top];
        stack[++top] = i;
    }

    for (int i = 0; i < queriesRowSize; ++i) {
        int a = queries[i][0];
        int b = queries[i][1];
        int meet = nextGreater[a];
        while (meet < heightsSize && meet <= b && nextGreater[b] != meet) {
            meet = nextGreater[meet];
        }
        ans[i] = (meet < heightsSize && meet <= b) ? meet : -1;
    }

    free(nextGreater);
    free(stack);
    return ans;
}
using System;
using System.Collections.Generic;

public class Solution {
    public int[] FindMeetBuilding(int[] heights, int[][] queries) {
        int n = heights.Length;
        int[] nextGreater = new int[n];
        Array.Fill(nextGreater, n);
        Stack<int> stack = new Stack<int>();

        for (int i = n - 1; i >= 0; --i) {
            while (stack.Count > 0 && heights[stack.Peek()] <= heights[i]) {
                stack.Pop();
            }
            if (stack.Count > 0) {
                nextGreater[i] = stack.Peek();
            }
            stack.Push(i);
        }

        int[] ans = new int[queries.Length];
        for (int i = 0; i < queries.Length; ++i) {
            int a = queries[i][0], b = queries[i][1];
            int meet = nextGreater[a];
            while (meet < n && meet <= b && nextGreater[b] != meet)
                meet = nextGreater[meet];
            ans[i] = (meet < n && meet <= b) ? meet : -1;
        }
        return ans;
    }
}

The Python solution utilizes a list to simulate a stack. It processes the heights in reverse order to fill the next greater element array and then handles each query accordingly.

Complexity

Time Complexity: O(n + q)
Space Complexity: O(n)

Try this approach in the editor

Approach 2: Binary Search on Preprocessed Data

Another approach is to store a list of building heights and their indices and utilize binary searching techniques to efficiently find the first building both Alice and Bob can move to. This approach prioritizes efficient query handling by using sorted data structures.

#include <stdio.h>
#include <stdlib.h>

int compare(const void* a, const void* b) {
    return (*(int**)a)[1] - (*(int**)b)[1];
}

int binarySearch(int** buildings, int size, int start, int height) {
    int left = start, right = size - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (buildings[mid][1] > height) {
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }
    return left;
}

int* findMeetBuilding(int* heights, int heightsSize, int** queries, int queriesRowSize, int* queriesColSize, int* returnSize) {
    *returnSize = queriesRowSize;
    int* ans = (int*)malloc(sizeof(int) * queriesRowSize);
    int** buildings = (int**)malloc(heightsSize * sizeof(int*));
    for (int i = 0; i < heightsSize; i++) {
        buildings[i] = (int*)malloc(2 * sizeof(int));
        buildings[i][0] = i; // index
        buildings[i][1] = heights[i]; // height
    }

    qsort(buildings, heightsSize, sizeof(int*), compare);

    for (int i = 0; i < queriesRowSize; ++i) {
        int a = queries[i][0];
        int b = queries[i][1];
        int posA = binarySearch(buildings, heightsSize, a+1, heights[a]);
        int posB = binarySearch(buildings, heightsSize, b+1, heights[b]);
        if (posA < heightsSize && posB < heightsSize && posA == posB && buildings[posA][0] > b) {
            ans[i] = buildings[posA][0];
        } else {
            ans[i] = -1;
        }
    }

    for (int i = 0; i < heightsSize; i++) {
        free(buildings[i]);
    }
    free(buildings);
    return ans;
}

The C solution preprocesses the building indexes based on their heights for efficient query handling. It then uses binary search to find potential meeting points for each query.

Complexity

Time Complexity: O(n log n + q log n)
Space Complexity: O(n)

Try this approach in the editor

Approach 3: Binary Indexed Tree

Let's denote queries[i] = [l_i, r_i], where l_i \le r_i. If l_i = r_i or heights[l_i] < heights[r_i], then the answer is r_i. Otherwise, we need to find the smallest j among all j > r_i and heights[j] > heights[l_i].

We can sort queries in descending order of r_i, and use a pointer j to point to the current index of heights being traversed.

Next, we traverse each query queries[i] = (l, r). For the current query, if j > r, then we loop to insert heights[j] into the binary indexed tree. The binary indexed tree maintains the minimum index of the suffix height (after discretization). Then, we judge whether l = r or heights[l] < heights[r]. If it is, then the answer to the current query is r. Otherwise, we query the minimum index of heights[l] in the binary indexed tree, which is the answer to the current query.

The time complexity is O((n + m) times log n + m times log m), and the space complexity is O(n + m). Where n and m are the lengths of heights and queries respectively.

Similar problems:

class BinaryIndexedTree {
    private n: number;
    private c: number[];
    private inf: number = 1 << 30;

    constructor(n: number) {
        this.n = n;
        this.c = Array(n + 1).fill(this.inf);
    }

    update(x: number, v: number): void {
        while (x <= this.n) {
            this.c[x] = Math.min(this.c[x], v);
            x += x & -x;
        }
    }

    query(x: number): number {
        let mi = this.inf;
        while (x > 0) {
            mi = Math.min(mi, this.c[x]);
            x -= x & -x;
        }
        return mi === this.inf ? -1 : mi;
    }
}

function leftmostBuildingQueries(heights: number[], queries: number[][]): number[] {
    const n = heights.length;
    const m = queries.length;
    for (const q of queries) {
        if (q[0] > q[1]) {
            [q[0], q[1]] = [q[1], q[0]];
        }
    }
    const idx: number[] = Array(m)
        .fill(0)
        .map((_, i) => i);
    idx.sort((i, j) => queries[j][1] - queries[i][1]);
    const tree = new BinaryIndexedTree(n);
    const ans: number[] = Array(m).fill(-1);
    const s = [...heights];
    s.sort((a, b) => a - b);
    const search = (x: number) => {
        let [l, r] = [0, n];
        while (l < r) {
            const mid = (l + r) >> 1;
            if (s[mid] >= x) {
                r = mid;
            } else {
                l = mid + 1;
            }
        }
        return l;
    };
    let j = n - 1;
    for (const i of idx) {
        const [l, r] = queries[i];
        while (j > r) {
            const k = n - search(heights[j]) + 1;
            tree.update(k, j);
            --j;
        }
        if (l === r || heights[l] < heights[r]) {
            ans[i] = r;
        } else {
            const k = n - search(heights[l]);
            ans[i] = tree.query(k);
        }
    }
    return ans;
}
const inf int = 1 << 30

type BinaryIndexedTree struct {
	n int
	c []int
}

func NewBinaryIndexedTree(n int) BinaryIndexedTree {
	c := make([]int, n+1)
	for i := range c {
		c[i] = inf
	}
	return BinaryIndexedTree{n: n, c: c}
}

func (bit *BinaryIndexedTree) update(x, v int) {
	for x <= bit.n {
		bit.c[x] = min(bit.c[x], v)
		x += x & -x
	}
}

func (bit *BinaryIndexedTree) query(x int) int {
	mi := inf
	for x > 0 {
		mi = min(mi, bit.c[x])
		x -= x & -x
	}
	if mi == inf {
		return -1
	}
	return mi
}

func leftmostBuildingQueries(heights []int, queries [][]int) []int {
	n, m := len(heights), len(queries)
	for _, q := range queries {
		if q[0] > q[1] {
			q[0], q[1] = q[1], q[0]
		}
	}
	idx := make([]int, m)
	for i := range idx {
		idx[i] = i
	}
	sort.Slice(idx, func(i, j int) bool { return queries[idx[j]][1] < queries[idx[i]][1] })
	s := make([]int, n)
	copy(s, heights)
	sort.Ints(s)
	ans := make([]int, m)
	tree := NewBinaryIndexedTree(n)
	j := n - 1
	for _, i := range idx {
		l, r := queries[i][0], queries[i][1]
		for ; j > r; j-- {
			k := n - sort.SearchInts(s, heights[j]) + 1
			tree.update(k, j)
		}
		if l == r || heights[l] < heights[r] {
			ans[i] = r
		} else {
			k := n - sort.SearchInts(s, heights[l])
			ans[i] = tree.query(k)
		}
	}
	return ans
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Precompute the Next Greater Element

Time Complexity: O(n + q)
Space Complexity: O(n)

Binary Search on Preprocessed Data

Time Complexity: O(n log n + q log n)
Space Complexity: O(n)

Binary Indexed Tree–

Complexity analysis

ApproachTimeSpaceWhen to Use
Brute Force ScanO(n * q)O(1)Useful for understanding the movement rule before optimization
Next Greater Element + Binary LiftingO((n+q) log n)O(n log n)Efficient for many queries and direct navigation along next-greater chains
Monotonic Stack + Binary SearchO((n+q) log n)O(n)Cleaner implementation when maintaining ordered candidate buildings

Frequently asked questions

Is Find Building Where Alice and Bob Can Meet easy or hard?

The problem is rated Hard because it combines multiple concepts: monotonic stacks, query normalization, and efficient searching for the next valid building. The core next-greater idea is straightforward, but integrating it with fast query handling makes the problem challenging.

Find Building Where Alice and Bob Can Meet Python/Java solution

Python and Java implementations typically compute the next greater element array using a stack, then process queries using binary search or jump pointers. The preprocessing step is O(n), and each query is answered in O(log n) time, making the solution efficient for large inputs.

What is the best approach for Find Building Where Alice and Bob Can Meet?

The most common solution uses a monotonic stack to preprocess next greater buildings and then answers queries with logarithmic search. After normalizing each query so the left index comes first, the algorithm checks direct meeting conditions and otherwise searches for the first building to the right that exceeds the required height. This reduces query processing to O(log n).

How to solve Find Building Where Alice and Bob Can Meet in O((n+q) log n)?

Precompute next greater elements using a monotonic decreasing stack. For each query (a, b), ensure a ≤ b. If heights[a] < heights[b], they meet at b. Otherwise search to the right of b for the first building with height greater than heights[a], using binary search over a preprocessed candidate list or binary lifting over the next-greater chain.

Is Find Building Where Alice and Bob Can Meet asked at Google/Amazon/Meta?

Problems involving next greater elements, monotonic stacks, and query preprocessing are common in interviews at companies like Google, Amazon, and Meta. Variants of this problem test your ability to combine stack-based preprocessing with efficient query handling.

What data structure is used in Find Building Where Alice and Bob Can Meet?

The core data structure is a monotonic stack used to compute next greater elements. Some implementations also use binary lifting tables, segment trees, heaps, or binary search structures to answer queries efficiently after preprocessing.

What is the time complexity of Find Building Where Alice and Bob Can Meet?

The optimized solutions run in O((n + q) log n) time. Building the monotonic stack or next greater element structure takes O(n), and each query requires a logarithmic search or jump through preprocessed data. Space complexity ranges from O(n) to O(n log n) depending on whether binary lifting tables are used.

Comments

Now write it yourselfClose this page and solve Find Building Where Alice and Bob Can Meet in the editor, without looking.
Practise Find Building Where Alice and Bob Can Meet