#1754
Largest Merge Of Two Strings
MediumApproaches
💡
Intuition
Time O(n²)Space O(1)
The brute force approach involves generating all possible merges of the two strings and selecting the largest one. This is straightforward but inefficient, as it checks every combination.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an empty string 'merge'.
- 2Step 2: While either word1 or word2 is non-empty, compare the first characters of both strings.
- 3Step 3: Append the larger character to 'merge' and remove it from the respective string.
solution.py10 lines
1def largestMerge(word1, word2):
2 merge = ''
3 while word1 or word2:
4 if word1 > word2:
5 merge += word1[0]
6 word1 = word1[1:]
7 else:
8 merge += word2[0]
9 word2 = word2[1:]
10 return mergeℹ
Complexity note: The time complexity is O(n²) because in the worst case, we compare the strings word1 and word2 at each step, leading to a quadratic number of comparisons.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.