TIP102 Unit 1 Session 1 Advanced (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
Q: What is the input to the function?
words
and a character x
.Q: What is the expected output of the function?
words
that contain the character x
.Q: Should the function be case-sensitive?
Q: What should the function return if no words contain the character x
?
x
, the function should return an empty list.Q: Are there any constraints on the input?
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: []
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
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