Start learning free

LESSON 164 OF 348 · LOOPS - CHALLENGES

Get Full Names II in TypeScript: Looping in Steps of Two

Practice Read the full explanation

Given an array of strings names that contain first and last names adjecent to each other, return an array containing the full names (separated by one space)

Example:

Input:  names = ["John", "Doe", "Andy", "Smith", "Mary", "Johnson"]

Output:  ["John Doe", "Andy Smith", "Mary Johnson"]
STEP 1 OF 5
    Ctrl + Enter to check

    TYPESCRIPT · LOOPS - CHALLENGES

    Get Full Names 2 in TypeScript, explained

    Problem overview

    The method getFullNames(names) receives an array of strings in which first names and last names alternate: a first name, its last name, the next first name, its last name, and so on. It returns a new array with one full name per pair, with a single space between the two parts.

    For ["John", "Doe", "Andy", "Smith", "Mary", "Johnson"] the result is ["John Doe", "Andy Smith", "Mary Johnson"]. The input has six strings and the output has three, one for each pair, in the same order.

    Approach: visit every other index

    Every first name sits at an even index (0, 2, 4, ...) and its last name sits right after it, at the next odd index. So a loop that starts at 0 and moves forward two positions at a time lands on a first name every time. At each stop, names[i] is the first name and names[i + 1] is the last name. Join them with a space and add the result to an answer array.

    The alternative is to loop over every index and use an if to ask whether it is even or odd. Stepping by 2 avoids that test, and each iteration handles one whole person instead of half of one.

    Step by step

    1. Create answer as an empty array of strings, the place where each finished name will go.
    2. Write the loop with i starting at 0, running while i < names.length, and increasing with i += 2 instead of i++. The step is what makes i always a first name's index.
    3. Build the full name as a constant string: names[i], then a space, then names[i + 1], joined with +.
    4. Push the name onto answer. Pushing at the end keeps the pairs in their original order.
    5. Return answer after the loop. Putting the return inside the loop would end the method after the first pair.

    The solution in TypeScript

    class Solution {
        getFullNames(names: string[]): string[] {
            let answer: string[] = [];
            for (let i = 0; i < names.length; i += 2) {
                const name: string = names[i] + " " + names[i + 1];
                answer.push(name);
            }
            return answer;
        }
    }

    The type string[] means an array of strings, and it appears twice: as the parameter type and as the return type. These annotations are checked by the compiler but disappear from the JavaScript it writes, so they can't stop a wrong value at run time.

    The variable answer is declared with let although it is never reassigned. The array's contents change through push, but the variable always refers to the same array, so const would also work. The name inside the loop is a const, which is right because it is fixed once it has been computed. Each iteration creates a fresh name, so the constant causes no problem.

    The + operator joins strings when at least one side is a string. Here it is used to glue the first name, the space and the last name together. A template literal, `${names[i]} ${names[i + 1]}`, gives the same result.

    Complexity

    The loop makes n / 2 iterations for an input of length n. Each one builds a short string and pushes it, which is constant work for names of ordinary length. The time is O(n), because dropping the factor of one half doesn't change the growth. The answer array holds n / 2 strings, so the extra space is O(n).

    Edge cases and common mistakes

    • An empty array. The loop doesn't run and the result is [].
    • An odd number of strings. The lesson promises pairs, but with an odd length the last i points at a first name with no partner. Then names[i + 1] is undefined, and the concatenation produces text such as "C undefined". TypeScript does not warn about it here, since indexing an array gives a plain string type.
    • Using i++. The result would hold overlapping pairs such as "Doe Andy".
    • Forgetting the space. names[i] + names[i + 1] gives "JohnDoe".
    • Returning inside the loop, which gives back only the first name.

    Testing

    With ["John", "Doe", "Andy", "Smith"] the result is ["John Doe", "Andy Smith"]. With [] it is [], and with ["A", "B"] it is ["A B"].

    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free