Merge Strings Alternately - codepath/compsci_guides GitHub Wiki
TIP102 Unit 1 Session 2 Standard (Click for link to problem statements)
Problem Highlights
- 💡 Difficulty: Easy
- ⏰ Time to complete: 10 mins
- 🛠️ Topics: String Manipulation, 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
merge_alternately()
should take two strings word1 and word2 and merge them by alternating their letters. If one string is longer, the remaining letters should be appended to the merged string.
HAPPY CASE
Input: word1 = "wol", word2 = "oze"
Expected Output: "woozle"
Input: word1 = "hfa", word2 = "eflump"
Expected Output: "heffalump"
EDGE CASE
Input: word1 = "eyre", word2 = "eo"
Expected Output: "eeyore"
P-lan
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Define a function that uses a loop to merge characters from both strings alternately and handles any remaining characters after the loop.
1. Define the function `merge_alternately(word1, word2)`.
2. Initialize two pointers `i` and `j` to 0 and an empty list `result` to store the merged characters.
3. Use a while loop to iterate until the end of either string:
a. Append the character from `word1` at index `i` to `result` if `i` is less than the length of `word1`.
b. Append the character from `word2` at index `j` to `result` if `j` is less than the length of `word2`.
c. Increment both `i` and `j`.
4. After the loop, append any remaining characters from `word1` or `word2` to `result`.
5. Join `result` into a string and return it.
⚠️ Common Mistakes
- Forgetting to handle cases where one string is longer than the other.
- Not properly merging the strings in alternating order.
I-mplement
Implement the code to solve the algorithm.
def merge_alternately(word1, word2):
# Initialize pointers and the result string
i, j = 0, 0
result = []
# Loop to merge characters alternately
while i < len(word1) and j < len(word2):
result.append(word1[i])
result.append(word2[j])
i += 1
j += 1
# Append remaining characters from the longer string
if i < len(word1):
result.append(word1[i:])
if j < len(word2):
result.append(word2[j:])
# Join the list into a string and return
return ''.join(result)