Codepath

Find the Villian

TIP102 Unit 1 Session 1 Standard (Click for link to problem statements)

Problem Highlights

  • 💡 Difficulty: Easy
  • Time to complete: 5 mins
  • 🛠️ Topics: Functions, Lists, Loops

U-nderstand

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

  • Q: What should the function return if the villain is not found in the crowd?
    • A: The function should return an empty list [].
  • Q: How does the function handle multiple occurrences of the villain in the crowd?

    • A: The function should return a list of all indices where the villain is found.
  • The function find_villain(crowd, villain) should return a list of indices where the villain is found in the crowd.

HAPPY CASE
Input: lst = ['Batman', 'The Joker', 'Alfred Pennyworth', 'Robin', 'The Joker', 'Catwoman', 'The Joker'], target = 'The Joker'
Expected Output: [1, 4, 6]

EDGE CASE
Input: lst = [], target = 'The Joker'
Expected Output: []

Input: lst = ['Batman', 'Superman'], target = 'The Joker'
Expected Output: []

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Iterate through the crowd list, checking each element against the villain, and store the indices where they match.

1. Define the function `find_villain(crowd, villain)`.
2. Initialize an empty list `indices` to store matching indices.
3. Use a loop to iterate through `crowd` with an index counter.
4. For each person in `crowd`, check if they match `villain`.
5. If they match, append the current index to `indices`.
6. Return the `indices` list.

⚠️ Common Mistakes

  • Forgetting to initialize the indices list.
  • Not incrementing the index counter correctly.

I-mplement

Implement the code to solve the algorithm.

def find_villain(crowd, villain):
    # Initialize an empty list to store the indices
    indices = []
    # Initialize the index counter
    index = 0
    
    # Iterate through the crowd list
    for person in crowd:
        # Check if the current person is the villain
        if person == villain:
            # If so, append the current index to the indices list
            indices.append(index)
        # Increment the index counter
        index += 1
    
    # Return the list of indices
    return indices
Fork me on GitHub