</>EmbeddedInterview
← All problems · Pointers & Strings

Reverse the Order of Words in a String In Place

Medium

Reverse the order of words in a writable NUL-terminated string without allocating another string. Words are separated by spaces. Preserve the spaces as produced by reversing the complete string, including repeated spaces. Implement void reverse_words(char *s).

Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.

Reverse the entire string, then reverse each individual word.

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <limits.h>
static void rev_chars(char *s,size_t n){for(size_t i=0;i<n/2;++i){char t=s[i];s[i]=s[n-1-i];s[n-1-i]=t;}}
void reverse_words(char *s)
{
    size_t n=strlen(s);
    rev_chars(s,n);
    for(size_t i=0;i<n;){
        if(s[i]==' '){++i;continue;}
        size_t j=i;while(j<n && s[j]!=' ')++j;
        rev_chars(s+i,j-i);i=j;
    }
}

The first reversal changes word order; the second restores the letters within each word. O(n) time and O(1) space.

solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
    char a[]="hello world", b[]="a b  c", c[]="", d[]="one";
    CHECK((reverse_words(a),strcmp(a,"world hello")==0));
    CHECK((reverse_words(b),strcmp(b,"c  b a")==0));
    CHECK((reverse_words(c),strcmp(c,"")==0));
    CHECK((reverse_words(d),strcmp(d,"one")==0));
    puts(fails ? "Some tests failed" : "All tests passed");
    return fails != 0;
}