How to contrary String inwards house inwards Java - Example

One of the mutual Java coding interview questions is to write a programme to contrary a String inwards house inwards Java, without using additional memory. You cannot purpose whatsoever library method e.g. StringBuilder to solve this problem. This restriction is placed because StringBuilder as well as StringBuffer course of didactics defines a reverse() method which tin easily contrary the given String. Since the principal objective of this enquiry is to assay out the programming logic of candidate, at that spot is no betoken giving him the pick to purpose the library method which tin brand this enquiry trivial. Now, how create yous solve this problem? Since String is backed past times a grapheme array, You tin purpose the same inwards house algorithm nosotros conduct maintain used to reverse an array inwards place. That technique uses the ii pointer approach where 1 pointer starts from the initiatory off as well as other pointer starts from the end. You swap elements until they meet. At that betoken of time, your String is already reversed.

The complexity of this algorithm is O(n/2) + fourth dimension taken inwards swapping, which effectively adds upwardly to O(n) time. This agency fourth dimension volition increase inwards the proportion of the length of String or lay out of characters on it.  The infinite complexity is O(1) because nosotros are non using whatsoever additional retentiveness to contrary the String.

Btw, String is a real pop topic on interviews as well as yous volition ofttimes regard a couplet of String based coding questions on interviews. You tin check, Introduction to Algorithms  by Thomas Cormen to larn to a greater extent than nearly pop String algorithms.

 One of the mutual Java coding interview questions is to  How to contrary String inwards house inwards Java - Example


Java Program to contrary String inwards place

Here is the uncomplicated representative to contrary characters inwards String past times using ii pointer technique. This is an in-place algorithm because it doesn't allocate whatsoever extra array, it only uses the ii int variables to concord positions from start as well as end. If yous expect closely this algorithm is similar to the algorithm nosotros conduct maintain used to reverse an array inwards place.

That's obvious because String is backed past times grapheme array inwards Java. If yous know how to contrary an array inwards house thus reversing a String is non dissimilar for you.  What is to a greater extent than of import is checking for null as well as empty String because this is where many programmers expire lazy as well as started writing code without validating input.


You must write your best code during programming interviews. The code which tin stand upwardly the assay out of fourth dimension inwards production is what every interview similar to see.  If yous don't know how to write production lineament code, I advise yous conduct maintain a expect at Clean Code, 1 of the books yous should read at the start of your programming career.

Here is the iterative algorithm to contrary String inwards place:

 One of the mutual Java coding interview questions is to  How to contrary String inwards house inwards Java - Example


Java Program to contrary a String inwards Place
import org.junit.Assert; import org.junit.Test;  /**  * Java Program to contrary a String inwards place,   * without whatsoever additional buffer inwards Java.  *  * @author WINDOWS 8  *  */ public class StringReversal {      /**      * Java method to contrary a String inwards house      * @param str       * @return  contrary of String      */     public static String reverse(String str) {         if(str == null || str.isEmpty()){             return str;         }         char[] characters = str.toCharArray();         int i = 0;         int j = characters.length - 1;         while (i < j) {             swap(characters, i, j);             i++;             j--;         }         return new String(characters);     }      /**      * Java method to swap ii numbers inwards given array      * @param str      * @param i      * @param j       */     private static void swap(char[] str, int i, int j) {         char temp = str[i];         str[i] = str[j];         str[j] = temp;     }      @Test     public void reverseEmptyString(){         Assert.assertEquals("", reverse(""));     }          @Test     public void reverseString(){         Assert.assertEquals("cba", reverse("abc"));     }          @Test     public void reverseNullString(){         Assert.assertEquals(null, reverse(null));     }          @Test     public void reversePalindromeString(){         Assert.assertEquals("aba", reverse("aba"));     }          @Test     public void reverseSameCharacterString(){         Assert.assertEquals("aaa", reverse("aaa"));     }          @Test     public void reverseAnagramString(){         Assert.assertEquals("mary", reverse("yram"));     } } 

You powerfulness conduct maintain too noticed that this time, I conduct maintain non purpose the main() method to assay out the code, instead I conduct maintain written couplet of JUnit assay out cases. It's genuinely improve to write unit of measurement assay out cases all the fourth dimension to assay out your code instead of using main() method equally it lay unit of measurement testing inwards your habit.

Btw, if yous experience reluctance on writing unit of measurement tests or non certain how to write tests, I advise yous read Test Driven, 1 of the best majority on Test drive evolution but fifty-fifty if yous don't follow TDD, it volition assist yous to write improve code as well as unit of measurement tests.

 One of the mutual Java coding interview questions is to  How to contrary String inwards house inwards Java - Example

I conduct maintain written next JUnit tests to banking concern gibe whether our contrary method is working for dissimilar kinds of String or not, the JUnit assay out final result is too attached below:
  • Unit assay out to contrary an empty String
  • Test to contrary a cypher String
  • Reverse a palindrome String
  • Unit tests to contrary a 1 grapheme string
  • JUnit assay out to contrary string alongside the same character
  • Reverse a String alongside dissimilar character
  • Reverse an anagram String

as well as hither is the final result of running these JUnit tests:

 One of the mutual Java coding interview questions is to  How to contrary String inwards house inwards Java - Example



You tin regard that all the unit of measurement tests are passing, which is good. You tin too add together to a greater extent than unit of measurement assay out to farther assay out our method of revrsing String inwards Java.

That's all nearly how to contrary String inwards house inwards Java. This is a mutual algorithm which uses ii pointer approach. Since it remove us to traverse the array till middle, fourth dimension complexity is O(n/2) i.e. O(n). It doesn't purpose whatsoever external buffer instead only purpose ii variables to expire on rail of indices from start as well as end.

Other String based coding problems from Interviews:
  • How to print all permutations of a String using recursion? (solution)
  • How to contrary String inwards Java without StirngBuffer? (solution)
  • How to count the lay out of words inwards given String? (solution)
  • How to banking concern gibe if a String is a palindrome inwards Java? (solution)
  • How to abide by duplicate characters on String? (solution)
  • How to count vowels as well as consonants inwards given String? (solution)
  • How to contrary words inwards a given String inwards Java? (solution)

Subscribe to receive free email updates:

0 Response to "How to contrary String inwards house inwards Java - Example"

Posting Komentar