Codepath

Words Containing Character

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

Problem Highlights

  • 💡 Difficulty: Easy
  • Time to complete: 10 mins
  • 🛠️ Topics: Arrays, Strings, Iteration

U-nderstand

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

  • Q: What is the input to the function?

    • A: The input is a list of strings words and a character x.
  • Q: What is the expected output of the function?

    • A: The function should return a list of indices representing the words in words that contain the character x.
  • Q: Should the function be case-sensitive?

    • A: Yes, the function should be case-sensitive, meaning it distinguishes between uppercase and lowercase characters.
  • Q: What should the function return if no words contain the character x?

    • A: If no words contain the character x, the function should return an empty list.
  • Q: Are there any constraints on the input?

    • A: The character x is assumed to be a single character, and the list words can contain any number of strings.
  • The function words_with_char() should take a list of strings words and a character x, and return a list of indices representing the words that contain the character x.

HAPPY CASE
Input: words = ["batman", "superman"], x = "a"
Expected Output: [0, 1]

Input: words = ["black panther", "hulk", "black widow", "thor"], x = "a"
Expected Output: [0, 2]

EDGE CASE
Input: words = ["star-lord", "gamora", "groot", "rocket"], x = "z"
Expected Output: []

Input: words = [", "superman", "], x = "a"
Expected Output: [1]

Input: words = [", ", "], x = "a"
Expected Output: []

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Iterate through the list of words and check if the character x is present in each word. If it is, append the index of that word to the result list.

1. Initialize an empty list `indices` to store the result.
2. Iterate through the list `words` using an index `i`.
    a. If the character `x` is in the word at index `i`, append `i` to `indices`.
3. Return `indices`.

⚠️ Common Mistakes

  • Forgetting to handle cases where the list words is empty.
  • Incorrectly checking if the character x is in the word.

I-mplement

Implement the code to solve the algorithm.

def words_with_char(words, x):
    indices = []
    
    for i in range(len(words)):
        if x in words[i]:
            indices.append(i)
    
    return indices
Fork me on GitHub