-2

I am attempting an array reversal problem.

Input array: s=["h","e","l","l","o"]

class Solution(object):
    def reverseString(self, s):
        """
        :type s: List[str]
        :rtype: None Do not return anything, modify s in-place instead.
        """

        left = 0
        right = len(s) - 1
        
        print (left)
        print (right)
        
        while left < right:
            s[left], s[right] = s[right], s[left]
            
            left = left + 1
            right = right - 1 

The code above runs successfully. However, when I adjust the line of code below: while left<right it errors and I'm really confused as to why:

while left < right:
            s[left] = s[right]
            s[right] = s[left]

Below are the results:

  • my output: ["o","l","l","l","o"]
  • expected: ["o","l","l","e","h"]

I'm super confused as to what is going on here. Can someone explain please?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
PineNuts0
  • 4,740
  • 21
  • 67
  • 112
  • When you do `s[left] = s[right]`, what are the contents of `s[left]` and `s[right]`? What happens when you subsequently do `s[right] = s[left]`? I suggest you should take a look at [How to debug small programs.](//ericlippert.com/2014/03/05/how-to-debug-small-programs/) and [What is a debugger and how can it help me diagnose problems?](//stackoverflow.com/q/25385173/843953). Knowing how to debug your programs is an important part of being able to write good code. – Pranav Hosangadi Jun 15 '22 at 23:29
  • 1
    For an explanation on what is happening in the `a,b = b,a` syntax, see https://stackoverflow.com/questions/14836228/is-there-a-standardized-method-to-swap-two-variables-in-python – Pranav Hosangadi Jun 15 '22 at 23:31

2 Answers2

4

In your first code block, the line s[left], s[right] = s[right], s[left] updates both elements of the array simultaneously. In the second example, you update s[left] first and s[right] subsequently. Thus, in the second update line s[right] = s[left], s[left] has already updated to the value of s[right] and this line is ineffective.

emmacb
  • 99
  • 6
0
// Recursive C++ program to reverse an array
#include <iostream>
using namespace std;

void  revarr(int arr[], int start , int end){
    if(start >= end)
    return;
    
    int temp;
    
     temp = arr[start];
    arr[start]= arr[end];
     arr[end]= temp;
    
    // Calling reverse function
    revarr(arr , start + 1 , end-1);

}

int main(){
    int arr[] = { 5 , 2 ,7 ,8 ,11 , 13 , 15 };
    int n = 7;
    for(int i=0;i< n ; i++){
        cout << arr[i] << " " <<endl;
}
        revarr(arr, 0 , n-1);
        
        cout<< "Array after reverse" <<endl;
        
        for(int i=0;i< n ; i++){
        cout << arr[i] << " ";
        
        }
        
    return 0;
}
  • Hello, please add more details than code to your answers here. E.g. some explantation as to why you'd choose this solution. – Destroy666 May 22 '23 at 20:57