Reverse position of words in a string using recursion

Carvia Tech | October 09, 2020 | | 0 views | Java Coding Challenges


In this article, we will write a program to reverse position of words in a given string using recursive approach.

Sample input

I am the best of bests

Output

bests of best the am I

Recursive Approach

  1. We will remove first word from the input string and append it at the end.

  2. Repeat it till all the words are removed and input becomes empty.

Java source

Reverse position of words in a string using Recusion Java
public class ReverseWordsInString {

    public String reverse(String input) {
        if (input.isEmpty()) {  (1)
            return input;
        }
        String[] arr = input.split(" ", 2);
        String firstWord = arr[0];
        String remainingSentence;
        if (arr.length == 2)
            remainingSentence = arr[1];
        else
            remainingSentence = "";
        return reverse(remainingSentence) + firstWord + " ";  (2)
    }
}
1 Base condition in recursion
2 Tail recursion - removes first word and appends it to the last

JUnit testcase

We will write a simple Junit based testcase to assert the correctness of our given program.

JUnit Test
import org.junit.Test;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.*;

public class ReverseWordsInStringTest {

    @Test
    public void reverse() {
        ReverseWordsInString utils = new ReverseWordsInString();
        assertThat(utils.reverse("I am the best of bests"), equalTo("bests of best the am I"));
    }
}

That’s all.


Java Coding Challenges:
  1. Check if the given string is palindrome
  2. Find two numbers of which the product is maximum in an array
  3. Check a number is Prime: Java Coding Problem
  4. Create anagram buckets from a given input array of words
  5. Anagrams string checker in Java
  6. Program to reverse a string using recursion in Java
  7. Java Program to find Factorial of a number
See all articles in Java Coding Challenges
Top articles in this category:
  1. Program to reverse a string using recursion in Java
  2. Write a program to reverse the order of words in a string
  3. SDET Java Coding Challenges
  4. Create anagram buckets from a given input array of words
  5. Get distinct words from a given file in Java
  6. 50 SDET Java Interview Questions & Answers
  7. Java Program to find Factorial of a number


Find more on this topic:
SDET Interviews image
SDET Interviews

SDET Java Interview pattern and collection of questions covering SDET coding challenges, automation testing concepts, functional, api, integration, performance and security testing, junit5, testng, jmeter, selenium and rest assured

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info