Start learning free

LESSON 149 OF 347 · LOOPING OVER ARRAY INDICES

Reverse Array in C#: Looping Backwards Over Indices

Practice Read the full explanation

Given an array of integers nums, return an array containing the integers in reverse order, without using built-in functions.

Example:

Input: nums = [2, 9, 1, 5, 8]
Output: [8, 5, 1, 9, 2]

Note:

Do not use builtin functions such as reverse(), it would defy the purpose of the challenge. Write the whole code yourself.

STEP 1 OF 4
    Ctrl + Enter to check

    C# · LOOPING OVER ARRAY INDICES

    Reverse Array in C#, explained

    Problem overview

    The method Reverse receives an array of integers, nums, and returns the same numbers in reverse order as a List<int>. The lesson asks you to write the loop yourself instead of calling a built-in reverse.

    For nums = [2, 9, 1, 5, 8] the result is [8, 5, 1, 9, 2]. The last element comes first, the second to last comes second, and so on until the first element comes last.

    Approach: read from the end, append to a new list

    The input array isn't touched. The method builds a new list and fills it by visiting the input from the last index down to the first. Because each element is appended after the previous one, the list ends up in reverse order of the input.

    Here is the idea on [2, 9, 1, 5, 8]. The last valid index is 4, because the array has five elements:

    • i = 4 adds 8, giving [8].
    • i = 3 adds 5, giving [8, 5].
    • i = 2 adds 1, giving [8, 5, 1].
    • i = 1 adds 9, giving [8, 5, 1, 9].
    • i = 0 adds 2, giving [8, 5, 1, 9, 2].

    Step by step

    1. Create an empty list named answer. Its element type is int, to match the return type.
    2. Loop backwards. Start i at nums.Length - 1, the last valid index, keep going while i >= 0, and subtract one after each pass. The condition is >= 0 because index 0 must be processed too.
    3. Append the element at i. answer.Add(nums[i]) puts it at the end of the list.
    4. Return the list once the loop is finished.

    The solution in C#

    class Solution {
        public List<int> Reverse(int[] nums) {
            List<int> answer = new List<int>();
            for (int i = nums.Length - 1; i >= 0; i--) {
                answer.Add(nums[i]);
            }
            return answer;
        }
    }
    

    Some C# details that matter here:

    • Counting down. i-- decrements the index after each pass. The loop has the same three parts as a counting-up loop, just with the start, the condition and the step all flipped.
    • Signed index. i is an int, so it can reach -1 and make the condition false. An unsigned type such as uint would wrap around to a huge number instead, and the loop would never stop correctly. Stay with int for array indices.
    • Length versus Count. Arrays use Length. The result is a List<int>, which would use Count.
    • Naming. The method is called Reverse. The standard library also has Array.Reverse and a LINQ Reverse method, which is what the lesson asks you not to rely on. Inside Solution there is no clash, since the call is to your own method.

    Complexity

    Time: O(n), where n is the length of nums. Each element is visited once and appended once. A list append takes constant time on average, and any occasional resizing of the list is spread across many appends.

    Space: O(n) for the new list, which holds as many integers as the input. The input array isn't modified. Reversing in place would use O(1) extra space, by swapping elements from both ends toward the middle, but this lesson asks for a new list.

    Edge cases and common mistakes

    • Empty array. The start index is -1, so the condition -1 >= 0 fails immediately and the method returns an empty list. No special case is needed.
    • One element. The loop runs once for index 0 and returns a list with that same element.
    • Starting at nums.Length. That index is one past the end, and reading nums[nums.Length] throws an IndexOutOfRangeException. The start must be nums.Length - 1.
    • Stopping at > 0. This skips index 0, so the first element of the input is missing from the answer.
    • Using i++ in a backwards loop. The index would climb past the end and the loop would never stop in the right place.
    • Negative numbers and duplicates. They behave like any other value, because the method copies elements without comparing them. [3, -1, 3] becomes [3, -1, 3], and [1, 2, 2] becomes [2, 2, 1].

    Testing

    • [2, 9, 1, 5, 8] gives [8, 5, 1, 9, 2].
    • [1, 2] gives [2, 1].
    • [7] gives [7].
    • [] 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