Reorder a String by Alternating Its Front and Back Characters
Capital OneSoftware Engineer · Online AssessmentLast updated
Rearrange a string by taking characters alternately from its front and its back: first, last, second, second-to-last and so on until every character is used once. Tests clean index handling for even and odd lengths and building the result efficiently for long inputs.
Given a string s, build a new string by taking characters alternately from the front and the back of s: the first character, then the last character, then the second character, then the second-to-last character, and so on, until every character of s has been used exactly once.
Function Signature
def reorder_front_back(s: str) -> str:
Rules
- Let
n = len(s). The output iss[0],s[n-1],s[1],s[n-2],s[2],s[n-3], and so on, stopping as soon asncharacters have been written. - Every position of
sis used exactly once, so the output also has lengthn. Whennis odd, the middle characters[n // 2]is the last one written. - Characters are copied unchanged.
Constraints
1 <= len(s) <= 10^5sconsists of lowercase English letters.
Examples
Example 1
Input: s = "abcdef"
Output: "afbecd"
The characters are taken in the order a (first), f (last), b (second), e (second-to-last), c, d.
Example 2
Input: s = "hello"
Output: "hoell"
The order is h (first), o (last), e (second), l (second-to-last), and finally the middle l.
Example 3
Input: s = "x"
Output: "x"
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.