Identifying Gems in a Collection Using Hash Sets
Problem Overview
Given a string gem_types representing the different categories of precious stones, and another string inventory representing the stones in your possession, determine how many of the stones you own are actually precious. Each character in inventory represents a single stone.
Constraints:
- Characters are case-sensitive (e.g.,
aandAare distinct). - The length of both strings ranges from 1 to 50.
- Both strings consist solely of English letters.
- All characters in
gem_typesare unique.
Examples:
- Input:
gem_types = "aA",inventory = "aAAbbbb"-> Output:3 - Input:
gem_types = "z",inventory = "ZZ"-> Output:0
Algorithm Strategy
The objective is to count the occurrences of characters from gem_types within the inventory string. To optimize the lookup process, transform gem_types into a hash set. This data structure allows for O(1) average time complexity when checking for element existence. Iterate through each character in the inventory, and if the character exists in the hash set, increment the total count.
Implementation
def calculate_precious_count(gem_definitions: str, owned_items: str) -> int:
unique_gems = set(gem_definitions)
return sum(1 for item in owned_items if item in unique_gems)
if __name__ == "__main__":
target_gems = input("Enter gem types: ")
my_stones = input("Enter your inventory: ")
print(f"Total gems found: {calculate_precious_count(target_gems, my_stones)}")