Identifying Endangered 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 count how many of the observed species are also considered endangered.
    • What input is provided?
      • Two strings, endangered_species and observed_species.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Use a set for fast lookup of endangered species and iterate through the observed species to count how many are endangered.

1) Convert `endangered_species` to a set for fast lookup.
2) Initialize a counter `count` to 0.
3) Iterate through `observed_species`:
   - If the species is in the endangered set, increment the counter.
4) Return the counter.

⚠️ Common Mistakes

  • Forgetting that species are case-sensitive.

I-mplement

def count_endangered_species(endangered_species, observed_species):
    # Create a set of endangered species for fast lookup
    endangered_set = set(endangered_species)
    
    # Count the number of endangered species in the observed species
    count = 0
    for species in observed_species:
        if species in endangered_set:
            count += 1
            
    return count