Start learning free

LESSON 164 OF 338 · LOOPS - CHALLENGES

Get Full Names II in Go: 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

    GO · LOOPS - CHALLENGES

    Get Full Names 2 in Go, explained

    Problem overview

    The function getFullNames receives a slice of strings, names, in which first names and last names alternate: a first name, then its last name, then the next first name, and so on. It returns a new slice of full names, each first name joined to its last name with one space.

    For ["John", "Doe", "Andy", "Smith", "Mary", "Johnson"] the pairs are John and Doe, Andy and Smith, Mary and Johnson. The result is ["John Doe", "Andy Smith", "Mary Johnson"]. The result has half as many elements as the input.

    Approach: visit every second element

    Every full name starts at an even index: 0, 2, 4, and so on. The last name is always at the next index. So a loop that moves by 2 lands on each first name exactly once, and the element after it is the matching last name.

    For each such index i, join names[i], a space and names[i+1], and add the result to a slice that the function returns at the end.

    Step by step

    1. Create the result slice. Declare answer as an empty slice of strings. It can start empty because append grows it as needed.
    2. Loop over even indices. Use a for loop with i starting at 0 and a step of i += 2, so i always points at a first name.
    3. Build the full name. Inside the loop, declare name as names[i] plus a space plus names[i+1]. The + operator joins strings.
    4. Save it. Append name to answer and assign the result back to answer.
    5. Return after the loop. Returning inside the loop would end the function after the first pair.

    The solution in Go

    func getFullNames(names []string) []string {
        answer := []string{}
        for i := 0; i < len(names); i += 2 {
            name := names[i] + " " + names[i+1]
            answer = append(answer, name)
        }
        return answer
    }
    

    Go details to notice:

    • The loop step. The post statement of a for can be any simple statement, so i += 2 works just as i++ does. There is no separate "step" syntax.
    • append returns a slice. It may have to allocate a bigger backing array, so it hands back the updated slice. Calling append(answer, name) and ignoring the result is a compile error, and writing answer = append(answer, name) is the only correct form.
    • []string{} against nil. []string{} is an empty, non-nil slice, while var answer []string is a nil slice. Both have length 0, print as [], and work with append. The lesson starts from the empty literal, so an empty input returns a slice that is empty but not nil.
    • Strings join with +. names[i] + " " + names[i+1] creates a new string. The space is a string literal in double quotes. A single-quoted ' ' would be a rune, which can't be added to a string.
    • := in the loop. name is a fresh variable on every iteration, because the declaration is inside the loop body.

    Complexity

    Let n be the length of names.

    Time: O(n). The loop runs n / 2 times. Each pass joins two strings and appends one element. Appending is cheap on average, since the slice grows in large steps.

    Space: O(n). The result holds n / 2 strings, each about as long as the two names combined.

    Edge cases and common mistakes

    • Empty input. With no names the loop never runs and the function returns an empty slice.
    • Odd length. The lesson's input always has pairs. If the length were odd, such as ["a", "b", "c"], the last pass would read names[3] and Go would stop with a run-time panic: index out of range [3] with length 3. Go checks every index, so an overrun is never silent.
    • Stepping by 1. With i++, the loop would pair "Doe" with "Andy" and produce twice as many results, mostly wrong ones.
    • Forgetting the space. names[i] + names[i+1] gives JohnDoe.
    • Dropping the assignment of append. The compiler rejects it, and it is a reminder that slices are values: the old variable still describes the old slice.
    • Returning inside the loop. Only the first full name would come back.

    Testing

    • ["John", "Doe", "Andy", "Smith", "Mary", "Johnson"] gives ["John Doe", "Andy Smith", "Mary Johnson"].
    • ["Ada", "Lovelace"] gives ["Ada Lovelace"].
    • [] gives [].
    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free