How to Reverse an Array in place - Java Coding Problems with Solution

It's relatively easy to reverse an array if you have the luxury to use another array, but how would you reverse an array if a temporary buffer is not allowed? This is one of the testing array interview questions, which often proved tricky for Java and other beginner Programmers. But, don't worry, I'll tell you how you can solve this problem without losing your cool. Well, you can also reverse an array in place without using an additional buffer. If you know how to access array elements and how to loop over an array in Java using traditional for loop, you can easily solve this problem without using additional space or in-place as described in many Algorithms books and courses, and on Coding interviews.

All you need to do is a loop over the array from start to the middle element and swap the first element to the last, second element to the second last until you reach the middle element. Once you reach the middle element, your array is already sorted and that too without using any additional space or in-place as asked in this question.

You can even use this algorithm to reverse a String in Java as well. After all, a String is backed by character array in Java and other programming languages like C and C++.  This is as simple as it could be, but you know, this is also the fastest way to reverse an array in Java.

In general, Data structure and Algorithm questions like ones based upon the array, linked list, binary tree, hash table, and searching/sorting algorithms are very important for programming job interviews and you should have a good knowledge of them.

If you feel that your data structure and algorithm skills are lacking or you want to learn them from scratch, I suggest you join a comprehensive course like Data Structures and Algorithms: Deep Dive Using Java on Udemy, which will teach you all of these and much more useful stuff on Algorithms. It's one of my favorite course on this topic.




How to Reverse an array in-place in Java

In the last section, I have explained you the logic or algorithm to reverse an array in place, now is the time to convert that algorithm into pseudo code and then real code in Java. You will also calculate the time and space complexity of our solution, which is often required in Interviews as well as on real-world to meet your performance SLA.

So, let's see an example of how you can reverse an array of String in Java in place.

This program doesn't use a temporary buffer or another array, instead, it just loops over the array and swap elements like starting from the first element, it swaps the first to last, second to the second last, until it reaches the middle of the array.

At this point all elements are already swapped, so your array is fully reversed.

This is a simple algorithm and time complexity is O(n/2) or O(n) because it needs to iterate over almost half the elements and perform n/2 swapping as well. The space complexity of the algorithm is O(1) because no matter how big the array is, it requires the same space.

Obviously, all in place algorithms has constant space complexity. Btw, if you have trouble understanding Big O notation and how to calculate time and space complexity of any arbitrary algorithm then I suggest you check out Algorithms and Data Structures - Part 1 and 2 courses on Pluralsight, which will teach you the technique of calculating these numbers.

Fastest way to reverse array in place in Java

This is an excellent course, but you need a Pluralsight membership to access this course which cost around $29 per month or $299 per annum.

This may seem a bit expensive but it's well worth of your money because it provides access to 5000+ latest technology online courses on Pluralsight, which is very important to keep yourself up-to-date.

I have been a Pluralsight member from last 3 years and I often got it on discount by paying just $199 and that's why I suggest every programmer have this membership if he can afford.

Btw, even if you don't have this membership, you can still access this course for free by using their 10-day Free Pass which allows 200 minutes of access to all their courses.




Java Program to Reverse an array of String in place

Here is our Java program which implements this algorithm to sort a String array. You can use this algorithm to sort any kind of arrays like a boolean array, int array, String array or any custom object array.

This is also the fastest way to reverse an array in Java. It cannot be faster than this because we are only accessing array which is constant time operation. The only thing you can optimize is to minimize swapping. Do you know any other way to make this algorithm faster? If yes, then please let us know.

If you want to solve this problem by using recursion instead of the iterative way (using for loop), you can customize your algorithm like below:

package coding;

import java.util.Arrays;

/**
 * Java Program to reverse array in place. Time complexity is O(n)
  *You cannot use additional buffer but one or two variables are fine.
 *
 * @author WINDOWS 8
 *
 */
public class ReverseArrayInPlace {
   
    public static void main(String args[]){
       
        String[] names = {"John", "Jammy", "Luke"};
        System.out.println("original array: " + Arrays.toString(names) );
       
        // reversing array with three elements
        reverse(names);
        System.out.println("reversed array: " + Arrays.toString(names) );
       
        String[] test = {"John"};
        System.out.println("original array: " + Arrays.toString(test) );
       
        // testing reverse array function with array of just one element
        reverse(test);
        System.out.println("reversed array: " + Arrays.toString(test) );
    }

    /**
     * Java Method to reverse String array in place
     *
     * @param array
     */
    public static void reverse(String[] array) {

        if (array == null || array.length < 2) {
            return;
        }

        for (int i = 0; i < array.length / 2; i++) {
            String temp = array[i];
            array[i] = array[array.length - 1 - i];
            array[array.length - 1 - i] = temp;
        }

    }

}

Output :
original array: [John, Jammy, Luke]
reversed array: [Luke, Jammy, John]
original array: [John]
reversed array: [John]

You can see from the output that our program is working fine for an odd number of elements. I haven't tested it for all kinds of input like reversing an array of the even number of elements, but I expect it to work.

Please drop a note, if you find any bug or issue and the program is not working for any input.


That's all about how to reverse an array in place in Java. This is one of the essential coding exercises for Java programmers learning data structure and algorithms. Remember, it's an in-place algorithm hence, the space complexity is O(1) and time complexity of this solution is O(n). This is also the fastest way to reverse the array in Java.

Further Learning
Data Structures and Algorithms: Deep Dive Using Java
Algorithms and Data Structures - Part 1 and 2
Data Structures in Java: An Interview Refresher
Cracking the Coding Interview - 189 Questions and Solutions


Other array based coding problems for Interviews:
  • How to find the largest and smallest number in an array without sorting? (solution)
  • How to remove an element from an array in Java? (solution)
  • How to check if an array contains a particular value? (solution)
  • How to find duplicates from an unsorted array in Java? (solution)
  • How to find one missing number in a sorted array? (solution)
  • How to find all pairs in an array whose sum is equal to k (solution)
  • How to remove duplicates from an array in Java? (solution)
  • How to find a missing value from an array containing 1 to 100? (solution)
  • 50+ Data Structure and Algorithms Problems from Interviews (questions)
  • My favorite free courses to learn data Structure in depth (FreeCodeCamp)
  • Iterative PreOrder traversal in a binary tree (solution)
  • How to count the number of leaf nodes in a given binary tree in Java? (solution)
  • Recursive InOrder traversal Algorithm (solution)
  • 10 Free Data Structure and Algorithm Courses for Programmers (courses)
  • 100+ Data Structure Coding Problems from Interviews (questions)
Thanks for reading this article so far. If you like this Java Array tutorial then please share with your friends and colleagues. If you have any questions or feedback then please drop a comment.


P. S. - If you are looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check the Easy to Advanced Data Structures course on Udemy. It's authored by a Google Software Engineer and Algorithm expert and its completely free of cost.

2 comments:






  1. package com.test.integer;

    import java.util.Arrays;

    public class ReverseArrayInPlace {

    public static void main(String[] args) {
    int[] intArr = {1,2,3,4,5,6};

    int length = intArr.length;

    for(int i=0; i < length/2; i++){
    int temp = intArr[i];
    intArr[i] = intArr[(length-1)-i];
    intArr[(length-1)-i] = temp;
    }

    System.out.println(Arrays.toString(intArr));
    }
    }

    ReplyDelete
  2. public static String[] reverseStringField(String[] arr){
    String[] reverseArr= new String[arr.length];
    int j =0;
    for (int i = arr.length-1; i >=0; i--) {

    reverseArr[j] =arr[i] ;
    j++;
    }
    return reverseArr;
    }

    ReplyDelete