Interview #204: Coding - Reverse words. Write a method to reverse the position of words.
❓ Problem Statement:
Write a method that takes a string as an argument and reverses the position of words in the string. The individual words themselves should remain intact, but the order of the words should be reversed.
Disclaimer: For QA-Testing Jobs, WhatsApp us @ 91-6232667387
✅ Example:
Input:
"I am learning test automation"
Output:
"automation test learning am I"
✅ Key Requirements:
✅ 1. Solution in Java
public class WordReverser {
public static String reverseWords(String input) {
if (input == null || input.trim().isEmpty()) {
return "";
}
// Trim input and split by spaces using regex for multiple spaces
String[] words = input.trim().split("\\s+");
// Reverse the array
StringBuilder reversed = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
reversed.append(words[i]);
if (i != 0) {
reversed.append(" ");
}
}
return reversed.toString();
}
public static void main(String[] args) {
String input = " I am learning test automation ";
String output = reverseWords(input);
System.out.println("Reversed: " + output);
}
}
🧪 Output:
Reversed: automation test learning am I
✅ 2. Solution in Python
def reverse_words(sentence):
if not sentence or sentence.strip() == "":
return ""
# Split by whitespace and reverse
words = sentence.strip().split()
reversed_sentence = ' '.join(reversed(words))
return reversed_sentence
# Example
input_str = " I am learning test automation "
output = reverse_words(input_str)
print("Reversed:", output)
🧪 Output:
Reversed: automation test learning am I
✅ 3. Solution in JavaScript
function reverseWords(str) {
if (!str || str.trim() === "") return "";
let words = str.trim().split(/\s+/);
return words.reverse().join(" ");
}
let input = " I am learning test automation ";
let output = reverseWords(input);
console.log("Reversed:", output);
🧪 Output:
Reversed: automation test learning am I
✅ 4. Solution in C#
using System;
class WordReverser {
public static string ReverseWords(string input) {
if (string.IsNullOrWhiteSpace(input)) return "";
var words = input.Trim().Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
Array.Reverse(words);
return string.Join(" ", words);
}
static void Main() {
string input = " I am learning test automation ";
string result = ReverseWords(input);
Console.WriteLine("Reversed: " + result);
}
}
✅ 5. Time and Space Complexity Analysis
✅ 6. Edge Cases to Handle
✅ 7. Use Cases in Real Life
✅ 8. Conclusion
Reversing the position of words (not the characters) in a sentence is a common string manipulation problem often asked in coding interviews. It tests your understanding of:
By taking care of edge cases like multiple spaces and empty input, you can deliver a robust and production-grade solution.