Skip to content

Words Containing Character

Raymond Chen edited this page Aug 1, 2024 · 6 revisions

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.

  • 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 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
Clone this wiki locally