Question 1
Reverse Words in a String
Problem
Given a sentence, reverse the order of words in it while keeping each word intact.
Example:
Input: "Wipro is hiring freshers"
Output: "freshers hiring is Wipro"
Code
Java
import java.util.Scanner;
public class ReverseWords {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String sentence = sc.nextLine();
String[] words = sentence.trim().split("\\s+");
StringBuilder result = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
result.append(words[i]);
if (i != 0) result.append(" ");
}
System.out.println(result.toString());
}
}Python
sentence = input().strip()
words = sentence.split()
print(" ".join(reversed(words)))Time: O(N)Space: O(N)