Placement Prep

Reverse Every Word in a Sentence: C, Java, Python

Two-pointer algorithm and code in C, Java, and Python to reverse every individual word in a sentence while keeping word order unchanged.

By FACE Prep Team 6 min read
string-programming python c-programming java placement-prep coding-interview algorithms

Reversing every word in a sentence means flipping each word’s characters while keeping the words in their original positions: "Program" becomes "margorP", "to" becomes "ot", but the words stay in sequence.

This is interpretation one of two common variants. The other variant reverses word order instead ("Hello World""World Hello"). Both appear in placement coding rounds; the section on variants below covers the second form. Start here with interpretation one.

What “reverse every word” means

Given the input "Program to reverse a sentence using recursion", the expected output is:

margorP ot esrever a ecnetnes gnisu noisrucer

Verify each word from first principles:

  • Program (7 chars): P-r-o-g-r-a-m reversed character by character gives m-a-r-g-o-r-P = margorP
  • to (2 chars): t-o reversed gives o-t = ot
  • reverse (7 chars): r-e-v-e-r-s-e reversed gives e-s-r-e-v-e-r = esrever
  • a (1 char): a single character reverses to itself, so a stays a
  • sentence (8 chars): s-e-n-t-e-n-c-e reversed gives e-c-n-e-t-n-e-s = ecnetnes
  • using (5 chars): u-s-i-n-g reversed gives g-n-i-s-u = gnisu
  • recursion (9 chars): r-e-c-u-r-s-i-o-n reversed gives n-o-i-s-r-u-c-e-r = noisrucer

Note: the single-character word "a" is a common bug source. It reverses to itself, but solutions that skip words of length 1 will produce wrong output. Confirm your implementation handles it.

Edge cases to test

Before submitting, run your solution against:

  • Single-character words: "a b c" should output "a b c" (unchanged). A single-character word reverses to itself.
  • Single word: "algorithm" should output "mhtirogla".
  • All identical characters: "aaa bbb" should output "aaa bbb" (unchanged). Useful sanity check that the swap loop is not corrupting the string.
  • String with leading or trailing spaces: behaviour depends on the problem spec. Python’s split() trims them automatically; a manual C loop needs explicit handling or you may attempt to reverse an empty word slice.
  • Empty string: return empty string without attempting a reversal. Passing an empty array to the two-pointer function causes undefined behaviour in C if the function dereferences the start index.
  • One word, all caps: "FACE" should output "ECAF".

Two-pointer algorithm

The two-pointer technique reverses a word by walking two indices toward each other and swapping characters at each step. It is the standard in-place approach for any single-array reversal task and requires no additional memory proportional to the input size.

To reverse the word at positions start through end in a character array:

  • Set left = start and right = end.
  • While left < right: swap the characters at left and right, then left++ and right--.
  • When left >= right, the word is fully reversed.

Trace for "to" (positions 8 and 9 in the example sentence):

  • Step 1: swap str[8] (‘t’) and str[9] (‘o’). Array now has ‘o’ and ‘t’. left = 9, right = 8.
  • Step 2: left >= right, loop exits. Result: "ot".

For the full sentence, wrap the single-word reversal in a boundary scan:

  • Walk the string with index i, tracking the start of the current word in start (initially 0).
  • When i hits a space or the null terminator: call the reversal on [start, i-1], then set start = i + 1.
  • Continue until the entire string is processed.

Each character is visited at most twice (once in the boundary scan, once in a swap). Time complexity is O(n). No extra array is allocated. The only bookkeeping variables are left, right, start, and one swap character, giving O(1) extra space.

Approach comparison

ApproachTimeExtra spaceNotes
Two-pointer in-place (C)O(n)O(1)Modifies original string directly
Split + reverse each (Python)O(n)O(n)Creates a list of word strings
StringBuilder per word (Java)O(n)O(n)New StringBuilder per word

For placement coding rounds, the time complexity is the same across all three. The space difference matters in embedded or memory-constrained contexts; for standard online judges it is not penalised.

Code in C, Java, and Python

C — two-pointer in-place

#include <stdio.h>
#include <string.h>

void reverse_word(char *str, int left, int right) {
    while (left < right) {
        char tmp = str[left];
        str[left] = str[right];
        str[right] = tmp;
        left++;
        right--;
    }
}

void reverse_each_word(char *str) {
    int n = strlen(str);
    int start = 0;
    for (int i = 0; i <= n; i++) {
        if (str[i] == ' ' || str[i] == '\0') {
            reverse_word(str, start, i - 1);
            start = i + 1;
        }
    }
}

int main() {
    char str[] = "Program to reverse a sentence using recursion";
    reverse_each_word(str);
    printf("%s\n", str);
    return 0;
}

Output: margorP ot esrever a ecnetnes gnisu noisrucer

The loop condition i <= n ensures the last word (not followed by a space) is reversed when i reaches strlen. A common off-by-one bug is stopping at i < n, which leaves the final word unreversed. Compiling with -Wall on GCC and adding an assert(str != NULL) guard at the top of the function are two low-effort ways to catch null-pointer and bounds issues during practice.

Java — StringBuilder.reverse()

Java’s StringBuilder class exposes a reverse() method that inverts the character sequence in-place. See the Java SE documentation for StringBuilder for the full API.

public class ReverseEachWord {
    public static String reverseEachWord(String sentence) {
        String[] words = sentence.split(" ");
        StringBuilder result = new StringBuilder();
        for (String word : words) {
            result.append(new StringBuilder(word).reverse());
            result.append(" ");
        }
        return result.toString().trim();
    }

    public static void main(String[] args) {
        System.out.println(reverseEachWord("Program to reverse a sentence using recursion"));
    }
}

Output: margorP ot esrever a ecnetnes gnisu noisrucer

The trim() call at the end removes the trailing space appended after the last word. Without it, the output has one extra space and will fail an online judge’s exact-match comparison.

Python — slice reversal

Python’s str.split() with no argument splits on any whitespace and discards empty tokens, so it handles multiple spaces cleanly. The [::-1] slice reverses any sequence.

def reverse_each_word(sentence: str) -> str:
    return ' '.join(w[::-1] for w in sentence.split())

print(reverse_each_word("Program to reverse a sentence using recursion"))
# margorP ot esrever a ecnetnes gnisu noisrucer

For a recursive version (common in older placement questions), define the function so it strips the first word, reverses it, and concatenates with a recursive call on the rest:

def reverse_each_word_recursive(sentence: str) -> str:
    words = sentence.split()
    if not words:
        return ""
    first_reversed = words[0][::-1]
    if len(words) == 1:
        return first_reversed
    return first_reversed + " " + reverse_each_word_recursive(" ".join(words[1:]))

print(reverse_each_word_recursive("Program to reverse a sentence using recursion"))
# margorP ot esrever a ecnetnes gnisu noisrucer

For practice on similar string and pattern problems, palindrome number pattern programs show how the same loop-control reasoning extends to multi-row output tasks.

Variant: reversing word order

The second interpretation flips the sequence of words while keeping each word’s characters intact:

  • Input: "Program to reverse a sentence using recursion"
  • Output: "recursion using sentence a reverse to Program"

Python one-liner: ' '.join(sentence.split()[::-1])

Java approach: split, iterate in reverse, rejoin.

String[] words = "Program to reverse a sentence using recursion".split(" ");
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());
// recursion using sentence a reverse to Program

Placement test tip: if the question says “reverse every word in a sentence”, expect interpretation one (characters reversed per word). If it says “reverse the sentence” or “reverse word order”, expect interpretation two. When the phrasing is ambiguous, check the provided sample output.

Where this appears in placement tests

String manipulation is a standard topic in the coding rounds of campus assessments for IT-sector roles. Problems asking for word reversal, palindrome checking, character frequency counts, and anagram detection appear regularly. Recruiters use these questions to probe loop control, off-by-one awareness, and how candidates handle edge cases.

The two-pointer technique comes up repeatedly because it applies to more than word reversal: it handles palindrome checking, in-place array operations, and sorted-array two-sum problems with the same mental model. Practising it on a word-reversal problem is a low-cost way to build a pattern that transfers across question types. For a broader view of what IT hiring looks like for fresh graduates in 2026, see IT jobs for freshers.

Output formatting discipline matters as much as the algorithm. The C implementation above appends no trailing space because the reversal is done in-place on the original string. The Java version trims explicitly. Missing a trim() or printing an extra newline causes a Wrong Answer verdict on automated judges. The same precision applies to formatted-output coding problems, where judges compare output character by character.

The split-and-reverse pattern this problem uses is also the first step in text preprocessing for language models: tokenise by whitespace, process each token, reassemble. Where that mental model moves from a placement-prep exercise to actual API calls is TinkerLLM (₹299 launch price): you apply the same split-process-join logic to prompt construction, not just a character array.

Primary sources

Frequently asked questions

What is the time complexity of reversing every word in a sentence?

O(n) where n is the total character count of the sentence. Each character is visited once to find word boundaries and once (at most) during the swap reversal, giving linear time overall.

How is reversing every word different from reversing word order?

Reversing every word flips each word's characters individually: 'Hello World' becomes 'olleH dlroW'. Reversing word order swaps positions: 'Hello World' becomes 'World Hello'. Placement tests use both; the problem statement is the signal.

Does the two-pointer approach work in-place without extra memory?

Yes. The two-pointer swap modifies the character array directly. Only two index variables and one temporary character are needed, so extra space is O(1) beyond the input string.

How should I handle multiple spaces between words?

Python's split() with no argument collapses consecutive whitespace and strips leading/trailing spaces. For a manual C loop, skip consecutive spaces before resetting the start index and ensure you do not attempt to reverse an empty word slice.

Does this type of string problem appear in campus placement tests?

String manipulation, including word-reversal variants, appears regularly in the coding rounds of IT-sector placement tests. The two-pointer technique and the split-reverse-join pattern are both standard expectations.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF