How to reverse an array without using extra space in O(n) time


Category: Data Structure And Algorithms Tags: C#

Input: arr = [1,2,3,4,5,6,7,8]

Output: arr = [8,7,6,5,4,3,2,1]


Like 0 People
Asked on 5 June 2021
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 165
Questions: 16
Given Best Solutions: 16 *

Answers:

Nikhil Joshi

Using technique of swapping two numbers without using extra space can work here.

    static void Main(string[] args)
    {
        int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };

        for (int i = 0; i < arr.Length / 2; i++)
        {
            // In first iteration
            // arr[0] = 1+8 = 9
            arr[i] += arr[arr.Length - i - 1];
            // arr[7] = 9-8 = 1
            arr[arr.Length - i - 1] = arr[i] - arr[arr.Length - i - 1];
            // arr[0] = 9-1 = 8
            arr[i] = arr[i] - arr[arr.Length - i - 1];
        }

        foreach (int element in arr)
            Console.WriteLine(element);
    }

Output:

8

7

6

5

4

3

2

1

Like 0 People on 5 June 2021

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User



x