Reverse Words - GCJ 2010 (Africa)

Below is a problem statement from the 'Google African Code Jam' (which is happening, at the moment):


Given a list of space separated words, reverse the order of the words. Each line of text contains L letters and W words. A line will only consist of letters and space characters. There will be exactly one space character between each pair of consecutive words.


The first line of input gives the number of cases, N.
N test cases follow. For each test case there will a line of letters and space characters indicating a list of space separated words. Spaces will not appear at the start or end of a line.


For each test case, output one line containing "Case #x: " followed by the list of words in reverse order.


Small dataset

N = 5
1 ≤ L ≤ 25

Large dataset

N = 100
1 ≤ L ≤ 1000

Sample Input

this is a test
all your base


Case #1: test a is this
Case #2: foobar
Case #3: base your all

The solution for the above problem is pretty easy. Below is my solution:


  1. Dear, Please don't mind if I am wrong. Please guide me if my solution is wrong.

    public class ReverseWords {

    public static void main(String p[]) {

    String input = "This is a test";

    String output[] = input.split(" ");

    for (int a = output.length - 1; a >= 0; a--) {
    System.out.print(output[a] + " ");


  2. Hello Shahid,
    The logic in your code, is the same as mine. So, if my solution is correct, your's should be too! :)

  3. Shahid i love the simplistic nature of your solution


Note: Only a member of this blog may post a comment.