TypeScript String Manipulation: Accessing Characters in Unique Patterns

Introduction

Hello, and welcome to our exciting exploration of TypeScript strings! For today's lesson, we've prepared something extraordinarily interesting: you will learn how to access characters from a string following a distinctive pattern. Our presentation is both comprehensive and concise, allowing you to master the concept promptly. Let's get started!

Task Statement

Imagine this: You receive a string from which you need to extract characters. However, the sequence in which you select them diverges from the norm. You start with the first character, then select the last character, move to the second character, then choose the second-to-last character, and continue this pattern until there are no characters left. Quite a mind-bender, isn't it?

Here's what we mean:

You are required to craft a TypeScript function:

function solution(inputString: string): string {
    // function implementation
}

This function takes inputString as a parameter, a string of lowercase English alphabet letters ('a' to 'z'), with a length ranging between 1 and 100 characters. The function then returns a new string, fashioned from the input string but with characters selected in the pattern we described above.

For example, if the inputString is "abcdefg", the function should return "agbfced". Here's how the pattern works step by step:

  1. Start with inputString: "abcdefg"

  2. Iteration 1:

    • Select First Character: 'a'
    • Select Last Character: 'g'
    • Intermediate Result: "ag"
  3. Iteration 2:

    • Select Second Character: 'b'
    • Select Second-to-Last Character: 'f'
    • Intermediate Result: "agbf"
  4. Iteration 3:

    • Select Third Character: 'c'
    • Select Third-to-Last Character: 'e'
    • Intermediate Result: "agbfce"
  5. Iteration 4 (for the middle character when length is odd):

    • Select Middle Character: 'd'
    • Final Result: "agbfced"

The function alternates between selecting characters from the start and end, continuing this sequence until it meets in the middle, resulting in the output "agbfced".

Solution Building: Step 1 - Initialization

Before we delve into the problem-solving aspect, let's arrange our result store. We initiate a variable, result, as an empty array to stockpile the output.

function solution(inputString: string): string {
    let result: string[] = [];
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal