Skip to content

Commit e7b5e89

Browse files
authored
Update Merge Strings Alternately - Leetcode 1768.py
1 parent e336bbd commit e7b5e89

File tree

1 file changed

+41
-2
lines changed

1 file changed

+41
-2
lines changed

Merge Strings Alternately - Leetcode 1768/Merge Strings Alternately - Leetcode 1768.py

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,38 @@
1+
# Brute Force Solution
2+
class Solution:
3+
def mergeAlternately(self, word1: str, word2: str) -> str:
4+
characters = ""
5+
cur_word = 1
6+
a, b = 0, 0
7+
8+
while a < len(word1) and b < len(word2):
9+
if cur_word == 1:
10+
characters += word1[a]
11+
a += 1
12+
cur_word = 2
13+
else:
14+
characters += word2[b]
15+
b += 1
16+
cur_word = 1
17+
18+
while a < len(word1):
19+
characters += word1[a]
20+
a += 1
21+
22+
while b < len(word2):
23+
characters += word2[b]
24+
b += 1
25+
26+
return characters
27+
# Let A be the length of Word1
28+
# Let B be the length of Word2
29+
# Let T = A + B
30+
31+
# Time: O(T^2)
32+
# Space: O(T)
33+
34+
35+
# Optimal Solution
136
class Solution:
237
def mergeAlternately(self, word1: str, word2: str) -> str:
338
A, B = len(word1), len(word2)
@@ -24,5 +59,9 @@ def mergeAlternately(self, word1: str, word2: str) -> str:
2459
b += 1
2560

2661
return ''.join(s)
27-
# Time: O(A + B) - A is Length of word1, B is Length of word2
28-
# Space: O(A + B) - A is Length of word1, B is Length of word2
62+
# Let A be the length of Word1
63+
# Let B be the length of Word2
64+
# Let T = A + B
65+
66+
# Time: O(T)
67+
# Space: O(T)

0 commit comments

Comments
 (0)