Start learning free

LESSON 149 OF 338 · LOOPING OVER ARRAY INDICES

Get Full Names in Go: Looping Over Slice Indices

Practice Read the full explanation

Given two arrays of strings named firstNames and lastNames, return an array containing the full names (separated by one space)

Example:

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

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

    GO · LOOPING OVER ARRAY INDICES

    Get Full Names in Go, explained

    Problem overview

    The function getFullNames receives two slices of strings, firstNames and lastNames. The name at position i in one slice belongs with the name at position i in the other. The function returns a new slice of full names, each one a first name, one space and a last name, in the original order.

    For firstNames = ["John", "Andy", "Mary"] and lastNames = ["Doe", "Smith", "Johnson"], the result is ["John Doe", "Andy Smith", "Mary Johnson"].

    Approach: one index, two slices

    The two slices are linked only by position, so a loop that walks the first slice by value would lose track of where it is in the second. A loop over the indices solves that: for each i, read firstNames[i] and lastNames[i], join them, and add the result to an answer slice. The loop touches each position once, so the work grows in step with the number of names.

    Step by step

    1. Start with an empty slice. names will collect the results. Writing it as []string{} gives a slice with length 0 that is ready to grow.
    2. Loop over the indices. for i := range firstNames runs once per element and sets i to 0, 1, 2 and so on. With a single variable, range gives you the index, not the element.
    3. Build the full name. The + operator joins strings, and the " " in the middle supplies the single space the output requires.
    4. Append it. append returns the grown slice, so its result must be assigned back to names.
    5. Return the slice after the loop, when it holds every full name.

    The solution in Go

    func getFullNames(firstNames []string, lastNames []string) []string {
        names := []string{}
        for i := range firstNames {
            name := firstNames[i] + " " + lastNames[i]
            names = append(names, name)
        }
        return names
    }
    

    The Go details worth knowing:

    • range with one variable. for i := range firstNames gives indices. To get both, write for i, first := range firstNames. Go rejects unused variables, which is why you can't write for i, first := range and then ignore first; use _ for a value you don't need.
    • := declares and infers the type. names := []string{} and name := ... create new variables inside the function. Plain = only assigns to a variable that already exists.
    • Why names = append(...). A slice is a small header pointing to an array. When the array is full, append allocates a bigger one and returns a header that points to it. Calling append(names, name) and discarding the result loses the new element, and Go reports that the result is unused.
    • Strings are immutable. The + creates a new string each time. The two input slices are never changed.

    Complexity

    With n names, the loop runs n times. Each pass joins two short strings and appends, and appending is amortized constant time, because the underlying array grows in large steps instead of one element at a time. Time is O(n) if you count names as the unit of work. The result slice holds n strings, so extra space is O(n).

    Edge cases and common mistakes

    • Empty input. Two empty slices give an empty result, because the loop body never runs. A nil slice works the same way: range over it does nothing.
    • Different lengths. The loop follows firstNames. If lastNames is shorter, lastNames[i] stops the program with an "index out of range" panic. For example, ["a", "b"] with ["x"] panics at i = 1. The lesson assumes both slices have the same length.
    • Forgetting the space. firstNames[i] + lastNames[i] gives "JohnDoe".
    • Dropping the result of append. append(names, name) on its own line does not compile.
    • Returning inside the loop. A return there would end the function after the first name.

    Testing

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