The O(n) Club: Reverse Words in a String – Where Your Spaces Go to Sabotage You

The O(n) Club: Reverse Words in a String – Where Your Spaces Go to Sabotage You

⚡ TL;DR

Given a messy string like ” Hello World from LeetCode “, put the words in reverse order, squish them together with single spaces, and stop at that—don’t flip letters! Java’s trim, split, and Collections.reverse do all the boring stuff. Here’s the one-liner hero:

// Basic Java fix for lazy devs
String input = "  Hello   World from  LeetCode  ";
String[] words = input.trim().split("\\s+");
Collections.reverse(Arrays.asList(words));
String result = String.join(" ", words); // output: "LeetCode from World Hello"
  

🧠 How Devs Usually Mess This Up

Everyone sees “reverse” and their hands tremble. You might feverishly reverse each character instead of just the words (nice try, but we’ve all been there). Others write three for-loops hunting phantom spaces and end up with output that looks like it lost a battle with regex. Or, they try some in-place char array sorcery, forgetting split() is already there—offering emotional support and working code. Don’t suffer.

🔍 What’s Actually Going On

Picture each word as a cocky developer at daily standup, each eager for spotlight. Your only job: make them line up in reverse. But this team loves chaos—spaces wander in, loiter everywhere, spill coffee on your formatting. Your task is to clear the floor and swap their order, leaving each word’s precious personality (spelling) untouched.

🛠️ PseudoCode

  • Trim off leading and trailing whitespace using trim().
  • Split the cleaned string into actual words: split("\\s+") handles a whole mob of spaces.
  • Reverse your shiny new String[]—just call Collections.reverse(Arrays.asList(words)), don’t get clever.
  • Reassemble: String.join(" ", ...) brings them back together like adults at a conference—one polite space at a time.
  • Step-by-step illustration:
    // Start with the worst-case whitespace
    String s = "   ab     cde    fg  ";
    s = s.trim();                        // "ab     cde    fg"
    String[] arr = s.split("\\s+");     // [ab, cde, fg]
    Collections.reverse(Arrays.asList(arr)); // [fg, cde, ab]
    String result = String.join(" ", arr);  // "fg cde ab"
        

💻 The Code

import java.util.*;
 public class ReverseWordsInString {
    public static String reverseWords(String s) {
        s = s.trim();
        String[] words = s.split("\\s+");
        Collections.reverse(Arrays.asList(words));
        return String.join(" ", words);
    }
     public static void main(String[] args) {
        String input = "  Hello   World from  LeetCode  ";
        System.out.println(reverseWords(input)); // LeetCode from World Hello
    }
}

⚠️ Pitfalls, Traps & Runtime Smacks

  • Split on single space? Welcome to bug city. Use split("\\s+"), not split(" "), or you’ll get ghosts (empty words) everywhere.
  • Empty input: ” ” should return “”. This code aces it.
  • Massive strings: Time/space is O(n), and that’s perfectly fine unless your interviewer thinks you’re building the next Google indexer.
  • Null input: LeetCode says “not my problem.” Defensive devs still check.

🧠 Interviewer Brain-Tattoo

“You don’t need to unscramble the alphabet soup, just swap the spoonfuls. And never trust a string with spare spaces—it’s up to something.”

Previous Article

The O(n) Club: Remove All Adjacent Duplicates in String — Now With 100% Less Regret Than Brute Force

Next Article

The O(n) Club: Average of Levels in a Binary Tree (Or Why Java Hates Decimals)