> For the complete documentation index, see [llms.txt](https://gl01.gitbook.io/gfg-editorials/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gl01.gitbook.io/gfg-editorials/2023/08-2023-aug-26/27-reverse-a-string.md).

# 27. Reverse a String

The problem can be found at the following link: [Question Link](https://practice.geeksforgeeks.org/problems/reverse-a-string/1)

## My Approach

Simply used a two-pointer approach to reverse the given string.

* I initialized two pointers, `i` and `j`, to the start and end of the string respectively.
* I swapped the characters at these pointers and moved `i` forward and `j` backward until they met in the middle of the string.

## Time and Auxiliary Space Complexity

* **Time Complexity**: The time complexity of this algorithm is `O(N/2)`, where `N` is the length of the input string. This is because we only need to swap characters up to the middle of the string.
* **Auxiliary Space Complexity**: The algorithm uses only a constant amount of extra space for the two pointers and the swapping operation, so the space complexity is `O(1)`.

## Code (C++)

```cpp
class Solution
{
public:
    string reverseWord(string str)
    {
        int i = 0, j = str.size() - 1;
        while (i < j)
        {
            swap(str[i], str[j]);
            ++i;
            --j;
        }

        return str;
    }
};
```

## Contribution and Support

For discussions, questions, or doubts related to this solution, please visit our [discussion section](https://github.com/getlost01/gfg-potd/discussions). We welcome your input and aim to foster a collaborative learning environment.

If you find this solution helpful, consider supporting us by giving a ⭐ star to the [getlost01/gfg-potd](https://github.com/getlost01/gfg-potd) repository.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gl01.gitbook.io/gfg-editorials/2023/08-2023-aug-26/27-reverse-a-string.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
