Skip to main content

Reverse a String

Problem​

You are given a string s. You need to reverse the string.

Examples:​

Example 1:

Input:
s = Geeks
Output: skeeG

Example 2:

Input:
s = for
Output: rof

Your Task:​

You only need to complete the function reverseWord() that takes s as parameter and returns the reversed string.

  • Expected Time Complexity: O(∣S∣)O(|S|)
  • Expected Auxiliary Space: O(1)O(1)

Constraints:​

1<=∣s∣<=100001 <= |s| <= 10000

Solution​

Python​

def reverseWord(self, str: str) -> str:
str = str[::-1]
return str

Java​

public static String reverseWord(String str) {
char ch;
String nstr = "";
for (int i=0; i<str.length(); i++) {
ch = str.charAt(i);
nstr = ch+nstr;
}
return nstr;
}

C++​

public:
string reverseWord(string str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
swap(str[left], str[right]);
left++;
right--;
}
return str;
}

C​

void reverseWord(char *str) {
int left = 0;
int right = strlen(str) - 1;
char temp;
while (left < right) {
temp = str[left];
str[left] = str[right];
str[right] = temp;
left++;
right--;
}
}
  • Time Complexity: O(n)O(n)
  • Auxiliary Space: O(1)O(1)