Approach
Sorting and greedy selection
For Path Existence Queries in a Graph II, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 53 lines of Python from the credited upstream file 3534.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def pathExistenceQueries(3 self,4 n: int,5 nums: list[int],6 maxDiff: int,7 queries: list[list[int]],8 ) -> list[int]:9 sortedNumAndIndexes = sorted((num, i) for i, num in enumerate(nums))10 sortedNums = [num for num, _ in sortedNumAndIndexes]11 indexMap = {originalIndex: sortedIndex for sortedIndex,12 (_, originalIndex) in enumerate(sortedNumAndIndexes)}13 maxLevel = n.bit_length() + 114 15 jump = [[0] * maxLevel for _ in range(n)]16 17 right = 018 for i in range(n):19 while right + 1 < n and sortedNums[right + 1] - sortedNums[i] <= maxDiff:20 right += 121 jump[i][0] = right22 23 for level in range(1, maxLevel):24 for i in range(n):25 prevJump = jump[i][level - 1]26 jump[i][level] = jump[prevJump][level - 1]27 28 def minJumps(start: int, end: int, level: int) -> int:29 """30 Returns the minimum number of jumps from `start` to `end` using binary31 lifting.32 """33 if start == end:34 return 035 if jump[start][0] >= end:36 return 137 if jump[start][level] < end:38 return math.inf39 for j in range(level, -1, -1):40 if jump[start][j] < end:41 break42 return (1 << j) + minJumps(jump[start][j], end, j)43 44 def minDist(u: int, v: int) -> int:45 uIndex = indexMap[u]46 vIndex = indexMap[v]47 start = min(uIndex, vIndex)48 end = max(uIndex, vIndex)49 res = minJumps(start, end, maxLevel - 1)50 return res if res < math.inf else -151 52 return [minDist(u, v) for u, v in queries]53