KatInterview

Interleave Characters from String Ends

StringsAuto-graded · 20 test cases
MediumAuto-gradedStringstwo-pointersstring-manipulationarray

Last 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 index len(s) - 1, then index 1, then len(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^5
  • s contains 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.