Storage manager

0

0 votes
Fenwick (Binary Indexed) Trees, Real world, Data Structures, Advanced Data Structures
Problem

Imagine you are the manager of a rental storage facility with N units. The units are represented by a 2D integer array of units where units[i]=[unitIdi,sizei] denotes that there is a unit with a unit number unitIdi and size equal to sizei. Each unitIdi is guaranteed to be unique.

Your customers have made K requests in a 2D array requests where requests[j]=[preferredj,minSizej]. The answer to the jth request is the unit number id of a unit such that:

The unit has a size of at least minSizej, and abs(idpreferredj) is minimized, where abs(x) is the absolute value of x. If there is no such unit, the answer is -1

Return an array answer of length K where answer[j] contains the answer to the jth request.

Note: If there is a tie in the absolute difference, then use the unit with the smallest such ID.

Example 1

Assumptions

Input

  • N = 3
  • units = [[2, 2], [1, 2], [3, 2]]
  • K = 3
  •  requests = [[3, 1], [3, 3], [5, 2]]

Output: 3 -1 3

Approach

First, unit number 3 is the closest as its size >=1 and abs(3-3)=0.

Second, no unit has a size greater or equal to 3.

Third, unit number 3 is the closest as its size >=2 and abs(5-3)=2.

Function description

Complete the function solve() provided in the editor. The function takes the following 4 parameters and returns the solution:

  • N: Represents the number of units
  • units: Represents the description of units
  • K: Represents the number of requests
  • requests: Represents the description of requests

Input format for custom testing

Note: Use this input format if you are testing against custom input or writing code in a language where we don’t provide boilerplate code

  • The first line contains N denoting the number of units.
  • Each of the next N lines contains the description of the ith unit.
  • The next line contains K denoting the number of requests.
  • Each of the next K lines contains the description of the jth request.

Output format

Print an array, representing the result to each query.

Constraints

1N1051K1041units[i][0],units[i][1],requests[j][0],requests[j][1]107

Sample Input
5
1 4
2 3
3 5
4 1
5 2
3
2 3
2 4
2 5
Sample Output
2 1 3
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

Given

Input

  • N = 5
  • units = [[1,4],[2,3],[3,5],[4,1],[5,2]]
  • K = 3
  •  requests = [[2,3],[2,4],[2,5]]

Output: 2 1 3

Approach 

First, unit number 2 is the closest as its size >=3 and abs(2-2)=0.

Second, unit1 and 3 both are suitable but 1 is used since its ID is smaller.

Third, unit 3 only has such a size.

Editor Image

?