Start learning free

LESSON 163 OF 347 · LOOPS - CHALLENGES

Get Full Names II in C#: Pairing Names with List<string>

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

    C# · LOOPS - CHALLENGES

    Get Full Names 2 in C#, explained

    Problem overview

    GetFullNames(string[] names) receives an array in which every first name is immediately followed by its last name. It returns a List<string> with one full name per pair, joined by a single space.

    For ["John", "Doe", "Andy", "Smith", "Mary", "Johnson"] the result is ["John Doe", "Andy Smith", "Mary Johnson"]. Six input strings make three output strings, so the result is half as long as the input.

    Approach

    The first names sit at the even indices 0, 2, 4, ... and each last name sits right after its first name. A loop that steps through the array two positions at a time lands on a first name on every pass, and names[i + 1] is its partner. Each pass builds one full name and stores it.

    The output size isn't known up front in a way that fits a fixed array neatly, and the return type is a List<string> anyway. A list starts empty and grows with Add, which suits collecting results one at a time.

    Step by step

    1. Create the result list. new List<string>() is an empty, growable list of strings, ready to be filled.
    2. Loop over the even indices. Writing the update as i += 2 makes i take the values 0, 2, 4, and so on.
    3. Build the full name. Concatenate names[i], a single space and names[i + 1] with +. The space is a separate string literal, " ".
    4. Add it to the list. Add appends at the end, so the full names keep the order of the input pairs.
    5. Return after the loop. Returning inside the loop would end the method after the first pair.

    The solution in C#

    class Solution {
        public List<string> GetFullNames(string[] names) {
            List<string> answer = new List<string>();
            for (int i = 0; i < names.Length; i += 2) {
                string name = names[i] + " " + names[i + 1];
                answer.Add(name);
            }
            return answer;
        }
    }
    

    Some C# details:

    • Arrays and lists use different size members. An array has a Length property, which the loop uses. A List<T> has Count. The method returns a list, so a caller asks it for Count.
    • List<T> lives in System.Collections.Generic. Code that uses it needs that namespace available.
    • Indexing is zero-based. The first element of names is names[0], and the last valid index is names.Length - 1.
    • Strings are immutable. The + expression creates a brand-new string for each pair and leaves the originals untouched.
    • The list can be built with the explicit type or with new(). List<string> answer = new(); is an equivalent shorter form in modern C#. The longer form above matches the lesson's code.

    Complexity

    Time: O(n), where n is the length of names. The loop makes n / 2 passes, and each one joins two short strings and adds one item to the list. List.Add takes constant time on average, because the list doubles its internal capacity when it fills up.

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

    Edge cases and common mistakes

    • Empty array. The loop doesn't run and an empty list comes back.
    • Odd length. If the array had an unpaired last name, say three entries, then names[i + 1] on the last pass would be out of range and throw an IndexOutOfRangeException. The task promises pairs, so the solution doesn't check for this.
    • Stepping by one. Using i++ would build "John Doe", then "Doe Andy", and so on, giving twice as many names, most of them wrong.
    • Forgetting the space. names[i] + names[i + 1] gives "JohnDoe". The task asks for exactly one space between the names.
    • Returning inside the loop. Only the first full name would be returned.
    • Using the wrong index for the last name. names[i - 1] pairs a name with the one before it, which is a first name when i is a last-name index. Because i only lands on first names, the partner is always i + 1.

    Testing

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