Array -DS

 Content of the page: 

  • Question
  • Approach
  • Complete Code Solution


Que -  Reverse the array






Approach - 
            
        We're going to use two pointer approach here the idea is to take two pointers one pointing at the start and one pointing at the end of the array and narrowing down the search space is

That is suppose we consider the first pointer i and second pointer j.


    int i = 0;
    int j = a.size() - 1;


Now we swap the values at index i and index j of the array and increase i by 1 and decrease J by 1.

        
        swap(a[i], a[j]);
        i++;
        j--;







Round 1 : 
Repeat the same while i is less than j. 
        
    
    while (i < j)
    {
        swap(a[i], a[j]);
        i++;
        j--;
    }



When the condition does not satisfy that i < j , break from the loop and return the final array.




Round 2 : 


Round 3 :
   
Condition for while loop does not satisfy.


Final Array :







Complete Code : 



    vector<int> reverseArray(vector<int> a)
    {
        int i = 0;
        int j = a.size() - 1;

        while (i < j)
        {
            swap(a[i], a[j]);
            i++;
            j--;
        }
    
        return a;
    }






Post a Comment

0 Comments