Data Structure to store Integer Range , Query the ranges and modify the ranges

后端 未结 2 605
离开以前
离开以前 2021-01-05 09:32

We need to maintain mobileNumber and its location in memory. The challenge is that we have more than 5 million of users and storing the location for each user will be like

相关标签:
2条回答
  • 2021-01-05 10:10

    Normally you can use specialized data structures to store ranges and implement the queries, e.g. Interval Tree.

    However, since phone number ranges do not overlap, you can just store the ranges in a standard tree based data structure (Binary Search Tree, AVL Tree, Red-Black Tree, B Tree, would all work) sorted only by [begin].

    For findLocation(number), use corresponding tree search algorithm to find the first element that has [begin] value smaller than the number, check its [end] value and verify if the number is in that range. If a match if found, return the location, otherwise the number is not in any range.

    For changeLocation() operation:

    1. Find the old node containing the number
    2. If an existing node is found in step 1, delete it and insert new nodes
    3. If no existing node is found, insert a new node and try to merge it with adjacent nodes.

    I am assuming you are using the same operation for simply adding new nodes.

    More practically, you can store all the entries in a database, build an index on [begin].

    0 讨论(0)
  • 2021-01-05 10:11

    First of all range = [begin;end;location]

    Use two structures:

    • Sorted array to store ranges begins
    • Hash-table to access ends and locations by begins

    Apply following algo:

    1. Use binary search to find "nearest less" value ob begin
    2. Use hash-table to find end and location for begin
    0 讨论(0)
提交回复
热议问题