Back to articles
Reverse an Array – Python Solution

Reverse an Array – Python Solution

via Dev.to PythonManoj Kumar

πŸ”„ Reverse an Array – Python Solution Hi All, Today I worked on a basic but important problem: Reversing an Array . πŸ“Œ Problem Statement Given an array, reverse its elements such that: First element becomes last Second element becomes second-last And so on πŸ” Example Example 1: arr = [ 1 , 4 , 3 , 2 , 6 , 5 ] Output: [ 5 , 6 , 2 , 3 , 4 , 1 ] Example 2: arr = [ 4 , 5 , 1 , 2 ] Output: [ 2 , 1 , 5 , 4 ] πŸ’‘ Approach πŸ”Ή Method 1: Using Two Pointers (Optimal) Use two pointers: start β†’ beginning of array end β†’ last index Swap elements until they meet πŸ’» Python Code (Two Pointer Method) def reverse_array ( arr ): start = 0 end = len ( arr ) - 1 while start < end : arr [ start ], arr [ end ] = arr [ end ], arr [ start ] start += 1 end -= 1 return arr πŸ” Dry Run For: arr = [ 1 , 4 , 3 , 2 ] Steps: Swap 1 and 2 β†’ [2, 4, 3, 1] Swap 4 and 3 β†’ [2, 3, 4, 1] Final Output: [ 2 , 3 , 4 , 1 ] πŸ–₯️ Sample Output Input: [1, 4, 3, 2, 6, 5] Output: [5, 6, 2, 3, 4, 1] Input: [4, 5, 1, 2] Output: [2, 1, 5, 4] 🧠 Alter

Continue reading on Dev.to Python

Opens in a new tab

Read Full Article
2 views

Related Articles