Interview #204: Coding - Reverse words. Write a method to reverse the position of words.

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:

  • Words are separated by one or more spaces.
  • The original words must not be reversed character-wise.
  • Leading/trailing spaces should be trimmed.
  • Multiple intermediate spaces should be reduced to a single space.


✅ 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

Article content

✅ 6. Edge Cases to Handle

Article content

✅ 7. Use Cases in Real Life

  • Reversing logs, chat transcripts, or feeds.
  • Command-line history manipulations.
  • Displaying most recent words or commands first.
  • Custom transformations in natural language processing (NLP).


✅ 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:

  • String splitting and trimming
  • Array manipulation
  • Clean code practices

By taking care of edge cases like multiple spaces and empty input, you can deliver a robust and production-grade solution.

Article content


To view or add a comment, sign in

Others also viewed

Explore topics