Concatenate - codepath/compsci_guides GitHub Wiki

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

Problem Highlights

  • 💡 Difficulty: Easy
  • Time to complete: 5 mins
  • 🛠️ Topics: String Manipulation, List Iteration, Return Statements

U-nderstand

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

  • Q: What should the function return if the list words is empty?

    • A: The function should return an empty string "".
  • Q: How does the function handle the elements in the list?

    • A: The function iterates through the list and concatenates each string element to form the final result.
  • The function concatenate() should take a list of strings and concatenate them into a single string. If the list is empty, it should return an empty string.

HAPPY CASE
Input: ["vengeance", "darkness", "batman"]
Output: "vengeancedarknessbatman"

EDGE CASE
Input: []
Output: "

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Define the function to iterate through the list and concatenate each string.

1. Define the function `concatenate(words)`.
2. Initialize an empty string `concatenated` to store the result.
3. Iterate through each word in `words`:
    a. Add the word to the `concatenated` string.
4. Return the `concatenated` string.

⚠️ Common Mistakes

  • Forgetting to handle the case when the list is empty.

I-mplement

Implement the code to solve the algorithm.

def concatenate(words):
    concatenated = ""  # Initialize an empty string to store the result
    
    # Iterate through each word in the list and add it to the result string
    for word in words:
        concatenated += word
    
    return concatenated