LeetCode Problem

How to Solve Path Existence Queries in a Graph II

To solve this problem, you'll leverage binary search over a valid answer space and sort the graph nodes based on their values. This allows you to efficiently check whether a path exists between queried nodes, considering the maximum allowed difference. The key challenge is managing large inputs and queries while maintaining a performant solution.

GhostInterview Help

Need help with Path Existence Queries in a Graph II without spending extra time grinding it?

GhostInterview can read Path Existence Queries in a Graph II from a screenshot, generate the answer path, explain the complexity, and support solver-first interview workflows when you need direct help fast.

Screenshot Input

Capture the prompt fast instead of rewriting the problem by hand.

Answer + Complexity

Get the solution path, trade-offs, and complexity summary in one pass.

Stealth Workflow

Stay outside captured layers on supported screen-share workflows.

Problem #3534Binary search over the valid answer spaceReviewed 2026-03-08
Difficulty
Hard
Primary pattern
Binary search over the valid answer space
Answer-first problem summary
Step-by-step approach and complexity
GhostInterview solver workflow

To solve this problem, you'll leverage binary search over a valid answer space and sort the graph nodes based on their values. This allows you to efficiently check whether a path exists between queried nodes, considering the maximum allowed difference. The key challenge is managing large inputs and queries while maintaining a performant solution.

Problem Statement

You are given a graph with n nodes, each node labeled from 0 to n-1. Each node has an associated value from an array nums of length n, and a maximum allowed difference maxDiff between nodes. An undirected edge exists between nodes i and j if the absolute difference between their corresponding values in nums is less than or equal to maxDiff.

For each query, you are given two nodes u and v. You need to determine if there is a path between u and v in the graph. Return an array of answers where each entry corresponds to whether a path exists for each query. Use efficient strategies to handle large input sizes and multiple queries.

Examples

Example 1

Input: n = 5, nums = [1,8,3,4,2], maxDiff = 3, queries = [[0,3],[2,4]]

Output: [1,1]

The resulting graph is:

Thus, the output is [1, 1] .

Example 2

Input: n = 5, nums = [5,3,1,9,10], maxDiff = 2, queries = [[0,1],[0,2],[2,3],[4,3]]

Output: [1,2,-1,1]

The resulting graph is:

Example 3

Input: n = 3, nums = [3,6,1], maxDiff = 1, queries = [[0,0],[0,1],[1,2]]

Output: [0,-1,-1]

There are no edges between any two nodes because: Thus, no node can reach any other node, and the output is [0, -1, -1] .

Constraints

  • 1 <= n == nums.length <= 105
  • 0 <= nums[i] <= 105
  • 0 <= maxDiff <= 105
  • 1 <= queries.length <= 105
  • queries[i] == [ui, vi]
  • 0 <= ui, vi < n

Solution Approach

To efficiently check connectivity, first sort the nodes based on their values in nums. For each query, you can perform binary search on the sorted array to quickly determine whether a path exists between nodes, considering the maxDiff constraint.

Union-Find data structure

Use a Union-Find (Disjoint-Set Union) data structure to group connected nodes. This allows efficient union and find operations, which helps in answering path existence queries quickly after sorting the nodes.

Answering the queries

After preprocessing the graph with sorting and union-find, answering each query becomes an O(1) operation. For each query, check if the two nodes are in the same connected component using the union-find structure.

Complexity Analysis

MetricValue
TimeDepends on the final approach
SpaceDepends on the final approach

The time complexity is dominated by the sorting step, which is O(n log n), followed by efficient union-find operations that are nearly constant time due to path compression and union by rank. The query answering step is O(1) for each query, making the total time complexity for answering all queries O(n log n + q), where q is the number of queries.

What Interviewers Usually Probe

  • Candidates should demonstrate familiarity with binary search and union-find techniques.
  • The ability to efficiently handle large input sizes and multiple queries is a key indicator of success.
  • Look for candidates who can clearly explain the reasoning behind sorting nodes and applying binary search.

Common Pitfalls or Variants

Common pitfalls

  • Failure to sort nodes properly before applying binary search can lead to incorrect results.
  • Not using the union-find structure efficiently may result in time complexity issues for large inputs.
  • Candidates may struggle with the time complexity of large numbers of queries and nodes if they don't optimize the solution properly.

Follow-up variants

  • Consider varying the maxDiff value to test different graph connectivity scenarios.
  • Test edge cases with a minimal number of nodes and queries to ensure robustness.
  • Introduce additional constraints such as larger arrays or more complex queries to challenge performance.

How GhostInterview Helps

  • GhostInterview provides a detailed walkthrough of the binary search approach and union-find optimization.
  • It offers hints on sorting nodes and how to apply the binary search technique for path existence queries.
  • GhostInterview simulates multiple query scenarios to help candidates practice their performance optimization techniques.

Topic Pages

FAQ

How do I approach the 'Path Existence Queries in a Graph II' problem?

Start by sorting the nodes based on their values in nums and use binary search to check the path existence. Union-find will help efficiently manage connectivity between nodes.

What is the time complexity of this problem?

The time complexity is O(n log n + q), where n is the number of nodes and q is the number of queries, due to sorting and union-find operations.

Can this problem be solved with a brute force approach?

While a brute force approach may work, it would be inefficient for large inputs, especially with many queries. Binary search and union-find are essential for optimal performance.

What role does the maximum difference maxDiff play in this problem?

The maxDiff value determines whether an edge exists between two nodes. Only nodes with values whose difference is less than or equal to maxDiff can be connected.

How does GhostInterview help with this problem?

GhostInterview walks through sorting the nodes, applying binary search, and using union-find to ensure efficient answers to path existence queries.

GhostInterview Solver

Need direct help with Path Existence Queries in a Graph II instead of spending more time grinding it?

Download GhostInterview when you want a LeetCode solver, not another long practice loop. Capture Path Existence Queries in a Graph II from a screenshot, get the answer path and complexity, and use supported stealth workflows that stay outside captured layers.

Screenshot Input

Capture the prompt fast instead of rewriting the problem by hand.

Answer + Complexity

Get the solution path, trade-offs, and complexity summary in one pass.

Stealth Workflow

Stay outside captured layers on supported screen-share workflows.