Tutorialspoint
Problem
Solution
Submissions

Reverse a Given String

Certification: Basic Level Accuracy: 48% Submissions: 50 Points: 5

Write a Python program to reverse a given string.

Example 1
  • Input: s = "hello"
  • Output: "olleh"
  • Explanation:
    • Step 1: Traverse the string from end to beginning.
    • Step 2: Append each character to a new string in reverse order.
    • Step 3: Return the new reversed string.
    • Step 4: For "hello", the reversed string is "olleh".
Example 2
  • Input: s = "Python"
  • Output: "nohtyP"
  • Explanation:
    • Step 1: Traverse the string from end to beginning.
    • Step 2: Append each character to a new string in reverse order.
    • Step 3: Return the new reversed string.
    • Step 4: For "Python", the reversed string is "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)
StringsData StructureAmazonGoogle
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.

Submitted Code :