Reverse a String or Array

Time Complexity : O(n) 

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.


//Here we have the full code

1:  #include <bits/stdc++.h>  
2:  using namespace std;  
3:  void rvereseArray(int arr[],int n)  
4:  {      
5:      int l=0;r=n-1;  
6:       while (l < r)  
7:       {  
8:            int temp = arr[l];   
9:            arr[l++] = arr[r];  
10:            arr[r--] = temp;  
11:       }   
12:  }        
13:  void printArray(int arr[], int size)  
14:  {  
15:      for (int i = 0; i < size; i++)  
16:      cout << arr[i] << " \n";  
17:  }   
18:  int main()   
19:  {  
20:       int arr[] = {1, 2, 3, 4, 5, 6};  
21:       int n = sizeof(arr) / sizeof(arr[0]);   
22:       printArray(arr, n);  
23:       rvereseArray(arr,n);  
24:       cout << "Reversed array is" << endl;  
25:       printArray(arr, n);  
26:       return 0;  
27:  }  

Post a Comment

0 Comments