HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Interview solutions to reverse a string and reverse a sentence

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
reverseinterviewsolutionssentenceandstring

Problem

Recently in an interview I was asked to

  • Write a method to reverse a string. I used StringBuilder but was asked not to use reverse method of builder but iterate over the string. Sample input/output provided by interviewer : "abc" --> "cba"



  • Next was to reverse a sentence. Sample input/output provided by interviewer : "hello world" --> "world hello"



Total time spent on both the solutions : around 10-12 minutes to write and run

Following is the code I wrote and I got rejected from interview. Would appreciate any helpful feedback.

class Solution {

  public static void main(String[] args) {
    String input = "hello world";
    System.out.println(reverseString(input));
    System.out.println(reverseSentence(input));
  }

  private static String reverseString(final String input){
    if(input == null || input.length() == 0){
      return null;
    }
    StringBuilder sb = new StringBuilder();
      for(int i =input.length()-1; i  >= 0; i--){
      sb.append(input.charAt(i));
    }
    return sb.toString();
  }

  private static String reverseSentence(final String input){

    final String[] wordsInInput = input.split(" ");
    StringBuilder sb = new StringBuilder();
    for(int i = wordsInInput.length-1; i >=0; i--){
      sb.append(wordsInInput[i]);
      sb.append(" ");
    }
    final String reversed = sb.toString();
    return reversed.trim();
  }
}

Solution

The reverse of an empty string should be an empty string, not null.

In reverseSentence(), the reversed.trim() call inefficiently copies the entire string, less one final space. You would have been better off shortening the StringBuilder instead of trimming the string.

All of your uses of final are excessive, I think. The final keyword merely prevents reassignment, and doesn't make anything more immutable than it already is. For short functions like this, writing final just adds noise.

Context

StackExchange Code Review Q#136110, answer score: 11

Revisions (0)

No revisions yet.