Codepath

Secret Identity

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

Problem Highlights

  • 💡 Difficulty: Easy
  • Time to complete: 10 mins
  • 🛠️ Topics: List Manipulation, In-place Modification

U-nderstand

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

  • Established a set (2-3) of test cases to verify their own solution later.
  • Established a set (1-2) of edge cases to verify their solution handles complexities.
  • Have fully understood the problem and have no clarifying questions.
  • Have you verified any Time/Space Constraints for this problem?
  • The function remove_name() should take a list people and a string secret_identity, and remove all instances of secret_identity from people in place.
HAPPY CASE
Input: people = ['Batman', 'Superman', 'Bruce Wayne', 'The Riddler', 'Bruce Wayne']
       secret_identity = 'Bruce Wayne'
Expected Output: ['Batman', 'Superman', 'The Riddler']

Input: people = ['Batman', 'Bruce Wayne', 'Superman', 'Bruce Wayne', 'Bruce Wayne']
       secret_identity = 'Bruce Wayne'
Expected Output: ['Batman', 'Superman']

EDGE CASE
Input: people = []
       secret_identity = 'Bruce Wayne'
Expected Output: []

Input: people = ['Batman', 'Superman', 'The Riddler']
       secret_identity = 'Bruce Wayne'
Expected Output: ['Batman', 'Superman', 'The Riddler']

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Iterate through the list and remove any instances of secret_identity.

1. Define the function `remove_name(people, secret_identity)`.
2. Initialize an index variable `i` to 0.
3. Use a while loop to iterate through `people`:
   - If the current element equals `secret_identity`, remove it using `pop`.
   - Otherwise, increment the index `i`.
4. Return the modified `people` list (although the function is in-place, returning it for clarity)

⚠️ Common Mistakes

  • Not accounting for the changing length of the list during iteration.
  • Not modifying the list in place.

I-mplement

Implement the code to solve the algorithm.

def remove_name(people, secret_identity):
    i = 0
    while i < len(people):
        if people[i] == secret_identity:
            people.pop(i)
        else:
            i += 1
Fork me on GitHub