Interleave Characters from String Ends
StringsAuto-graded · 20 test casesLast updated
Rebuild a string by alternately picking characters from opposite ends until all are consumed, testing two-pointer convergence logic.
You are given a string s. Construct a new string by repeatedly selecting characters from the leftmost and rightmost unused positions in alternation—starting with the leftmost, then the rightmost, then the next leftmost, and so on—until every character has been selected exactly once.
Write a function that returns this reconstructed string.
Function Signature
def interleave_ends(s: str) -> str:
Rules
- Begin by taking the character at index
0, then the character at indexlen(s) - 1, then index1, thenlen(s) - 2, continuing this pattern. - Stop once all
len(s)characters have been taken. - If the string has odd length, the middle character will be the final one selected.
- The output string has the same length as the input.
Constraints
1 <= len(s) <= 10^5scontains only lowercase English letters.
Examples
Example 1
Input: interleave_ends('abcdef')
Output: 'afbecd'
Example 2
Input: interleave_ends('hello')
Output: 'hoell'
Example 3
Input: interleave_ends('x')
Output: 'x'
Hints
Hint 1
Use two pointers starting at opposite ends of the string and move them toward each other.
Hint 2
When the pointers meet at the same position, that character should only be added once.
Hint 3
Build the result using a list and join at the end for optimal performance with large strings.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem asks us to build a new string by consuming characters from both ends of the input string in alternation. This pattern naturally suggests a two-pointer technique where one pointer starts at the beginning and another at the end, both moving toward the center.
Initialize left at index 0 and right at index n - 1. In each iteration, append s[left] to the result, then append s[right] (unless left equals right, which happens when there's a middle character in odd-length strings). After each pair, increment left and decrement right. Continue while left <= right.
The key detail is handling the middle character when the string has odd length. When left and right converge to the same index, we must add that character only once. The condition if left != right before appending s[right] ensures this.
Why This Works
The algorithm maintains a simple invariant: at the start of each iteration, all indices less than left and all indices greater than right have already been processed. The range [left, right] contains exactly the unprocessed characters.
Each iteration processes the endpoints of this range. When left < right, we take both endpoints. When left == right, only one character remains (the middle), and we take it once. The loop terminates when left > right, meaning no characters remain unprocessed.
This guarantees every character appears exactly once in the output, in the specified alternating order.
Complexity Analysis
Time Complexity: O(n) where n is the length of the string. We iterate approximately n/2 times, performing constant work per iteration. The final join operation is linear in the output size.
Space Complexity: O(n) for storing the result list. Since we must produce an output string of length n, this space usage is unavoidable and optimal.
Implementation Notes
We use a list to accumulate characters and join at the end rather than concatenating strings repeatedly. Python strings are immutable, so repeated concatenation can lead to O(n²) time complexity in the worst case. With the constraint that n can reach 10^5, list accumulation followed by a single join is the reliable approach.
Complete Solution
def interleave_ends(s: str) -> str:
n = len(s)
result = []
left, right = 0, n - 1
while left <= right:
result.append(s[left])
if left != right:
result.append(s[right])
left += 1
right -= 1
return "".join(result)