easystringtwo-pointerpattern: two-pointer

Reverse String

Reverse the input string. In-place is preferred where the language allows.

Problem

Statement

Read a single line from standard input and print it reversed.

The archetype "hello, world" of algorithm interviews — every language has a one-liner reversal, and the value of practising it is seeing how each language expresses the same idea. C++ has reverse(s.begin(), s.end()). Python has s[::-1]. Java has new StringBuilder(s).reverse().toString(). In assembly you write a loop.

Worked cases

Examples

Input
hello
Output
olleh
Input
racecar
Output
racecar
NoteA palindrome reads the same reversed.
Input
Output
NoteEmpty input → empty output.
Bounds

Constraints

  • 0 ≤ input length ≤ 10^5
  • ASCII input only — multi-byte UTF-8 handling is out of scope for the base problem.
Reference

Sample solutions

Runnable starter code. Click "Try in playground" to open pre-loaded with the test fixtures.

Python
print(input()[::-1])
Java
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.hasNextLine() ? sc.nextLine() : "";
        System.out.println(new StringBuilder(s).reverse().toString());
    }
}
C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    string s; getline(cin, s);
    reverse(s.begin(), s.end());
    cout << s << "\n";
}
Pattern

Practice this pattern

These problems solve on the same intuition — try one next while the pattern is fresh.

Also try