Tensorum
YouTubeसीखना शुरू करें
LeetCode 344 · Two Pointers

Reverse String

LeetCode 344 · आसान · समाधान, intuition और कदम-दर-कदम वॉकथ्रू

Swap s[i] with s[n−1−i] for i < n/2.

आसानTwo PointersString

मैंने Reverse String (LeetCode 344) ऐसे हल किया — Two Pointers पैटर्न का एक आसान प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।

नीचे का विवरण अंग्रेज़ी में है।

Intuition

Swap the first and last characters, then the second and second-to-last, and so on until the middle. Each swap fixes two positions.

Approach

  1. 1

    Loop i over the first half.

  2. 2

    Swap s[i] and s[n−i−1].

मैंने कैसे हल किया

Two-ended swapPythonO(n) time · O(1) space
class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        n=len(s)
        for i in range(n//2):
            s[i],s[n-i-1]=s[n-i-1],s[i]
        return s
        
स्टेप-थ्रू लोड हो रहा है…

Reverse String — अक्सर पूछे जाने वाले प्रश्न

Reverse String के पीछे intuition क्या है?

Swap the first and last characters, then the second and second-to-last, and so on until the middle. Each swap fixes two positions.

Reverse String (LeetCode 344) कैसे हल करें?

1. Loop i over the first half. 2. Swap s[i] and s[n−i−1].

Reverse String की time और space complexity क्या है?

Time: O(n)। Space: O(1)। (Accepted approach: Two-ended swap।)

Reverse String में आम गलतियाँ क्या हैं?

Stop at n // 2 or you'll swap everything back.