← 返回 coinbase 的题目列表Generate Random NFT
类型:online_judge
Design an algorithm to generate a random NFT (Non-Fungible Token). Suppose we have a sequence of NFTs, each with a unique identifier. The algorithm should be able to randomly return an NFT identifier in O(1) time complexity and allow quick addition or removal of NFT identifiers. Provide some initial sample data of NFT identifiers. Write unit tests to ensure the correctness and efficiency of the algorithm in performing random selection and sequence updates.
Test cases:
Initialize the sequence with ["nft1", "nft2", "nft3"], randomly select, one possible output is "nft2".
Add "nft4" and randomly select, possible output is "nft4".
Remove "nft2" and randomly select again, one possible output is "nft3".
Add "nft5" and perform multiple random selections to confirm "nft2" is removed.
Continuously add and remove multiple times to check edge cases.
Data scale:
The number of NFT identifiers ranges from 1 to 1000.
Each operation followed by a random selection should take O(1) expected time.
Example
Input
add_nft('nft1'), add_nft('nft2'), add_nft('nft3'), get_random_nft(), remove_nft('nft2'), get_random_nft(), add_nft('nft4'), get_random_nft()