Home Backend Development PHP Tutorial Find Building Where Alice and Bob Can Meet

Find Building Where Alice and Bob Can Meet

Dec 23, 2024 pm 09:55 PM

Find Building Where Alice and Bob Can Meet

2940. Find Building Where Alice and Bob Can Meet

Difficulty: Hard

Topics: Array, Binary Search, Stack, Binary Indexed Tree, Segment Tree, Heap (Priority Queue), Monotonic Stack

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

Hint:

  1. For each query [x, y], if x > y, swap x and y. Now, we can assume that x <= y.
  2. For each query [x, y], if x == y or heights[x] < heights[y], then the answer is y since x ≤ y.
  3. Otherwise, we need to find the smallest index t such that y < t and heights[x] < heights[t]. Note that heights[y] <= heights[x], so heights[x] < heights[t] is a sufficient condition.
  4. To find index t for each query, sort the queries in descending order of y. Iterate over the queries while maintaining a monotonic stack which we can binary search over to find index t.

Solution:

The problem requires determining the leftmost building where Alice and Bob can meet given their starting buildings and movement rules. Each query involves finding a meeting point based on building heights. This is challenging due to the constraints on movement and the need for efficient computation.

Key Points

  1. Alice and Bob can move to another building if its height is strictly greater than the current building.
  2. For each query, find the leftmost valid meeting point, or return -1 if no such building exists.
  3. The constraints demand a solution better than a naive O(n²) approach.

Approach

  1. Observations:

    • If a == b, Alice and Bob are already at the same building.
    • If heights[a] < heights[b], Bob's building is the meeting point.
    • Otherwise, find the smallest building index t > b where:

      • heights[a] < heights[t]
      • heights[b] <= heights[t] (as b is already less than a in height comparison).
  2. Optimization Using Monotonic Stack:

    • A monotonic stack helps efficiently track the valid buildings Alice and Bob can move to. Buildings are added to the stack in a way that ensures heights are in decreasing order, enabling fast binary searches.
  3. Query Sorting:

    • Sort the queries in descending order of b to process buildings with larger indices first. This ensures that we build the stack efficiently as we move from higher to lower indices.
  4. Binary Search on Stack:

    • For each query, use binary search on the monotonic stack to find the smallest index t that satisfies the conditions.

Plan

  1. Sort queries based on the larger of the two indices (b) in descending order.
  2. Traverse the array backward while maintaining a monotonic stack of valid indices.
  3. For each query, check trivial cases (a == b or heights[a] < heights[b]).
  4. For non-trivial cases, use the stack to find the leftmost valid building via binary search.
  5. Return the results in the original query order.

Solution Steps

  1. Preprocess Queries:

    • Ensure a <= b in each query for consistency.
    • Sort queries by b in descending order.
  2. Iterate Through Queries:

    • Maintain a monotonic stack as we traverse the array.
    • For each query:
      • If a == b, the answer is b.
      • If heights[a] < heights[b], the answer is b.
      • Otherwise, use the stack to find the smallest valid index t > b.
    • Binary Search on Stack:

      • Use binary search to quickly find the smallest index t on the stack that satisfies heights[t] > heights[a].
    • Restore Original Order:

      • Map results back to the original query indices.
    • Return Results.

    • Let's implement this solution in PHP: 2940. Find Building Where Alice and Bob Can Meet

      <?php
      /**
       * @param Integer[] $heights
       * @param Integer[][] $queries
       * @return Integer[]
       */
      function leftmostBuildingQueries($heights, $queries) {
          ...
          ...
          ...
          /**
           * go to ./solution.php
           */
      }
      
      /**
       * @param $queries
       * @return array
       */
      private function getIndexedQueries($queries) {
          ...
          ...
          ...
          /**
           * go to ./solution.php
           */
      }
      
      /**
       * @param $stack
       * @param $a
       * @param $heights
       * @return mixed|null
       */
      private function findUpperBound($stack, $a, $heights) {
          ...
          ...
          ...
          /**
           * go to ./solution.php
           */
      }
      
      class IndexedQuery {
          public $queryIndex;
          public $a; // Alice's index
          public $b; // Bob's index
      
          /**
           * @param $queryIndex
           * @param $a
           * @param $b
           */
          public function __construct($queryIndex, $a, $b) {
              $this->queryIndex = $queryIndex;
              $this->a = $a;
              $this->b = $b;
          }
      }
      
      // Test the function
      $heights = [6, 4, 8, 5, 2, 7];
      $queries = [[0, 1], [0, 3], [2, 4], [3, 4], [2, 2]];
      print_r(leftmostBuildingQueries($heights, $queries));
      
      $heights = [5, 3, 8, 2, 6, 1, 4, 6];
      $queries = [[0, 7], [3, 5], [5, 2], [3, 0], [1, 6]];
      print_r(leftmostBuildingQueries($heights, $queries));
      ?>
      
      Copy after login

      Explanation:

      1. Sorting Queries: The queries are sorted by b in descending order to process larger indices first, which allows us to update our monotonic stack as we process.
      2. Monotonic Stack: The stack is used to keep track of building indices where Alice and Bob can meet. We only keep buildings that have a height larger than any previously seen buildings in the stack.
      3. Binary Search: When answering each query, we use binary search to efficiently find the smallest index t where the conditions are met.

      Example Walkthrough

      Input:

      • heights = [6,4,8,5,2,7]
      • queries = [[0,1],[0,3],[2,4],[3,4],[2,2]]

      Process:

      1. Sort Queries:

        • Indexed queries: [(2,4), (3,4), (0,3), (0,1), (2,2)]
      2. Build Monotonic Stack:

        • Start at the highest index and add indices to the stack:
          • At index 5: Stack = [5]
          • At index 4: Stack = [5, 4]
          • ...
      3. Query Processing:

        • For query [0,1], heights[0] < heights[1]: Result = 2.
        • ...

      Output:

      [2, 5, -1, 5, 2]

      Time Complexity

      1. Query Sorting: O(Q log Q) where Q is the number of queries.
      2. Monotonic Stack Construction: O(N) where N is the length of heights.
      3. Binary Search for Each Query: O(Q log N).

      Overall: O(N Q log (Q N)).

      Output for Example

      Input:

      $heights = [6, 4, 8, 5, 2, 7];
      $queries = [[0, 1], [0, 3], [2, 4], [3, 4], [2, 2]];
      
      Copy after login

      Output:

      print_r(findBuilding($heights, $queries)); // [2, 5, -1, 5, 2]
      
      Copy after login

      This approach efficiently handles large constraints by leveraging a monotonic stack and binary search. It ensures optimal query processing while maintaining correctness.

      Contact Links

      If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!

      If you want more helpful content like this, feel free to follow me:

      • LinkedIn
      • GitHub

      The above is the detailed content of Find Building Where Alice and Bob Can Meet. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1672
14
PHP Tutorial
1276
29
C# Tutorial
1256
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO) How do you prevent SQL Injection in PHP? (Prepared statements, PDO) Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

See all articles