-
Notifications
You must be signed in to change notification settings - Fork 242
Words Containing Character
TIP102 Unit 1 Session 1 Advanced (Click for link to problem statements)
- 💡 Difficulty: Easy
- ⏰ Time to complete: 10 mins
- 🛠️ Topics: Arrays, Strings, Iteration
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 characterx
.
- A: The input is a list of strings
-
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 characterx
.
- A: The function should return a list of indices representing the words in
-
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.
- A: If no words contain the character
-
Q: Are there any constraints on the input?
- A: The character
x
is assumed to be a single character, and the listwords
can contain any number of strings.
- A: The character
-
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`.
- Forgetting to handle cases where the list words is empty.
- Incorrectly checking if the character x is in the word.
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