Count Unique Species - codepath/compsci_guides GitHub Wiki

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Q
    • What is the desired outcome?
      • To return the number of unique species counts after replacing non-digit characters with spaces and splitting the result.
    • What input is provided?
      • A string ecosystem_data consisting of digits and lowercase English letters.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Replace non-digit characters with spaces, split the resulting string by spaces, and count the unique species counts.

1) Iterate through `ecosystem_data` and replace non-digit characters with spaces.
2) Split the modified string by spaces to extract species counts.
3) Convert the species counts to integers and store them in a set.
4) Return the size of the set.

⚠️ Common Mistakes

  • Not correctly handling leading zeros in the species counts.

I-mplement

def count_unique_species(ecosystem_data):
    # Replace all non-digit characters with spaces
    modified_data = []
    for char in ecosystem_data:
        if char.isdigit():
            modified_data.append(char)
        else:
            modified_data.append(' ')
    modified_data = ''.join(modified_data)
    
    # Split the resulting string by spaces to get all species counts
    counts = modified_data.split()
    
    # Convert counts to integers to remove leading zeros and get unique counts
    unique_counts = set()
    for count in counts:
        if count:  # Ensure the count is not an empty string
            unique_counts.add(int(count))
    
    # Return the number of unique counts
    return len(unique_counts)