
Problem
Solution
Submissions
Reverse a Given String
Certification: Basic Level
Accuracy: 77.27%
Submissions: 198
Points: 5
Write a Python program to reverse a given string.
Example 1
- Input: "hello"
- Output: "olleh"
- Explanation:
- Step 1: Take the last character of "hello", which is "o".
- Step 2: Take the second last character, which is "l".
- Step 3: Take the third last character, which is "l".
- Step 4: Take the fourth last character, which is "e".
- Step 5: Take the fifth last character, which is "h".
- Step 6: Combine all characters in reverse order: "o" + "l" + "l" + "e" + "h" = "olleh".
- Step 7: Return the reversed string "olleh".
Example 2
- Input: "Python"
- Output: "nohtyP"
- Explanation:
- Step 1: Take the last character of "Python", which is "n".
- Step 2: Take the second last character, which is "o".
- Step 3: Take the third last character, which is "h".
- Step 4: Take the fourth last character, which is "t".
- Step 5: Take the fifth last character, which is "y".
- Step 6: Take the sixth last character, which is "P".
- Step 7: Combine all characters in reverse order: "n" + "o" + "h" + "t" + "y" + "P" = "nohtyP".
- Step 8: Return the reversed string "nohtyP".
Constraints
- 1 ≤ len(string) ≤ 10^6
- The string contains printable ASCII characters.
- Time Complexity: O(n), where n is the length of the string.
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use slicing to reverse the string:
s[::-1]
- Use a loop to build the reversed string.
- Handle edge cases where the string is empty or has only one character.