Given a string s, return the string with its characters in reverse order.
Reverse a String
SolvedExamples:
Input: s = "hello"
Output: "olleh"
Explanation: Reading the characters from the end gives olleh.
Input: s = "w3colleges"
Output: "segelloc3w"
Constraints:
1 ≤ s.length ≤ 10^5s contains printable ASCII characters without spaces
Expected Complexities
Time Complexity: O(n) Auxiliary Space: O(1)
Company Tags
Topic Tags
Swap the first and last characters, then the second and second-last, and keep moving inwards until the two pointers meet. That is n/2 swaps and no extra memory. In Python the slice s[::-1] does the same thing in one expression.
char *reverseString(char *s) {
int i = 0, j = strlen(s) - 1;
while (i < j) {
char t = s[i];
s[i++] = s[j];
s[j--] = t;
}
return s;
}
Sign in to see your submissions.