Data structure to handle the requirement of following use case

前端 未结 5 1791
梦谈多话
梦谈多话 2021-01-29 13:10

All the records in a database is saved in (key, value) pair formats.Records can always be retrieved by specifying key value. Data structure needs to be developed to handle follo

5条回答
  •  轮回少年
    2021-01-29 13:52

    Store the keys in a trie. For the numbers in your example (assuming 4 digit numbers) it looks like this:

    *root*
     |
     0 -- 2 - 5 - 6
     | |
     | +- 3 - 6 - 2
     | |
     | +- 8 - 7 - 4
     |
     1 - 4 - 5 - 2
    

    This data structure can be traversed in a way that returns (1) or (3). It won't be quite as fast for (3) as would maintaining an index for each digit, so I guess it's a question of whether space or lookup time is your primary concern. For (2), it is already O(log n), but if you need O(1), you could store the keys in both the trie and a hash table.

提交回复
热议问题