Home > Back-end >  Python Leetcode Reverse Array Using While Loop
Python Leetcode Reverse Array Using While Loop

Time:06-16

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?

CodePudding user response:

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.

CodePudding user response:

The built in reverse() function should solve your issue:

s.reverse()
  • Related