Split Concatenated Strings — LeetCode 555 Python Solution
MediumLeetCode PremiumGreedyArrayString
- Problem
- #555
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an array of strings strs. You could concatenate these strings together into a loop, where for each string, you could choose to reverse it or not.
Example
- Input
- strs = ["abc","xyz"]
- Output
- "zyxcba"
- Explanation
- You can get the looped string "-abcxyz-", "-abczyx-", "-cbaxyz-", "-cbazyx-", where '-' represents the looped status.
Python solution
Python
class Solution:
def splitLoopedString(self, strs: List[str]) -> str:
strs = [s[::-1] if s[::-1] > s else s for s in strs]
ans = ''.join(strs)
for i, s in enumerate(strs):
t = ''.join(strs[i + 1 :]) + ''.join(strs[:i])
for j in range(len(s)):
a = s[j:]
b = s[:j]
ans = max(ans, a + t + b)
ans = max(ans, b[::-1] + t + a[::-1])
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(n) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 555. Split Concatenated Strings is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 555. Split Concatenated Strings?
- LeetCode 555. Split Concatenated Strings is rated Medium on LeetCode.
- What is the time complexity of LeetCode 555. Split Concatenated Strings?
- The Python solution on this page runs in O(n^2).
- What is the space complexity of LeetCode 555. Split Concatenated Strings?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 555. Split Concatenated Strings cover?
- LeetCode 555. Split Concatenated Strings is tagged Greedy, Array and String on LeetCode.
- Is LeetCode 555. Split Concatenated Strings a premium problem?
- Yes. LeetCode 555. Split Concatenated Strings is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.