Practice › Strings
Reverse a String
Easy · Strings · Asked at TCS, Infosys, Wipro, Accenture, Cognizant
Given a string s, print it reversed.
Input
One line with the string s (only lowercase letters, no spaces).
Output
The reversed string.
Constraints
- 1 ≤ |s| ≤ 10^5
Example 1
Input
codify
Output
yfidoc
Example 2
Input
a
Output
a
Hints
- Swap the first and last characters, then move both ends inward.
- Stop when the two pointers meet in the middle.
Approach
Two pointers i = 0 and j = n − 1: swap s[i] and s[j], then i++ and j-- until they meet. That's n/2 swaps with no extra memory. Library helpers (reverse in C++, s[::-1] in Python, StringBuilder.reverse() in Java) do the same.
Complexity: O(n) time · O(1) extra space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
int i = 0, j = (int)s.size() - 1;
while (i < j) swap(s[i++], s[j--]);
cout << s << "\n";
return 0;
}Python solution
s = input().strip()
print(s[::-1])Java solution
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
System.out.println(new StringBuilder(s).reverse());
}
}