Tutorialspoint
Problem
Solution
Submissions

Reverse a Given String

Certification: Basic Level Accuracy: 77.39% Submissions: 199 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)
StringsAmazonGoogleTutorialspoint
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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.

The following are the steps to reverse the given string: 

  • Define a function: Create reverse_string(input_string)
  • Reverse the string: Use slicing [::-1]
  • Call the function: Pass "Hello, World!"
  • Store the result: Save it in reversed_string

Submitted Code :