Wednesday, May 1, 2024
HomeJava Easy methods to reverse an ArrayList in place in Java? Instance

[Solved] Easy methods to reverse an ArrayList in place in Java? Instance


You’ll be able to reverse an ArrayList in place in Java through the use of the identical algorithm now we have used to reverse an array in place in Java. When you have already solved that drawback then It is a no-brainer as a result of ArrayList is nothing however a dynamic array, which may resize itself. All components of an array are saved within the inner array itself. By the best way, if it’s essential to reverse an ArrayList then you need to be utilizing the Collections.reverse() methodology offered by the Java Assortment framework. It is a generic methodology, so you can’t solely reverse an ArrayList but additionally Vector, LinkedList, CopyOnWriteArrayList, or every other Listing implementation.

Although, value noting is that this methodology internally makes use of a ListIterator for reversing the listing, which could not be as environment friendly as our algorithm.

If this query is requested in an interview, then you may as well use recursion to reverse the ArrayList, as proven in this article. The interviewer usually exams the candidate with a recursive algorithm simply to verify in the event that they perceive recursion or not.

Additionally, fundamental information of important knowledge construction can also be essential and that is why I counsel all Java programmers be a part of a complete Knowledge Construction and Algorithms course like Knowledge Constructions and Algorithms: Deep Dive Utilizing Java on Udemy to fill the gaps in your understanding.

Easy methods to reverse an ArrayList in place in Java? Instance

Right here is code to reverse an ArrayList of String in place. The algorithm is generic, so you may as well use it to reverse an ArrayList of Integer, Double, or every other object. For those who look fastidiously, we’re simply iterating over the array and swapping components from the alternative finish till we attain the center of the listing. At this level, our listing is totally reversed. This is similar algorithm now we have used to reverse an array earlier.

        int dimension = listOfFood.dimension();
        for (int i = 0; i < dimension / 2; i++) {
            closing String meals = listOfFood.get(i);
            listOfFood.set(i, listOfFood.get(dimension - i - 1)); 
            listOfFood.set(dimension - i - 1, meals); 
        }

Although a few issues, you want to bear in mind. Since we’re utilizing the set() methodology, you can’t move an unmodifiable or read-only ArrayList to this methodology. Utilizing this algorithm with read-only ArrayList will throw java.lang.UnSupportedOperationException.

The time complexity of this algorithm is O(n/2) i.e. O(n) the place n is the scale of ArrayList, and house complexity is O(1) as a result of we do not want extra listing or house required by the recursive algorithm to reverse a listing in Java.

Another factor which it is best to take note this algorithm ought to solely be used with Listing which helps RandomAccess e.g. ArrayList and Vector. Although you possibly can reverse the LinkedList utilizing this algorithm, it is going to be of order O(n^2) as a result of the linked listing would not assist index-based entry and get() methodology traverse the linked listing to retrieve the specified factor.

Since traversal in a linked listing is O(n), the time complexity of algorithm rises to O(n^2) for reversing linked listing in place utilizing this algorithm.

On the identical word, in the event you got here listed below are a part of your programming job interview preparation, you must also verify Grokking the Coding Interview: Patterns for Coding Questions course on Educative.

It should train you important coding patterns like sliding window, merge intervals, quick and sluggish factors, and different approaches that may assist you to to resolve actual coding questions from reputed firms interviews like Fb, Amazon, Google, and Microsoft.

How to reverse an ArrayList in place in Java - Coding Interview Questions

.

Java Program to reverse an ArrayList in place

Right here is our pattern Java program to reverse an ArrayList of String in place. The algorithm is generic, so you may as well use it to reverse an ArrayList of Integer, Double, or every other object.

import java.util.ArrayList;
import java.util.Listing;

/*
 * Java Program to reverse an ArrayList in place.
 * Once you reverse ArrayList in place, you aren't
 * allowed to make use of extra buffer e.g. an array
 * or any assortment.
 */
public class ReverseArrayListInPlace {

    public static void essential(String args[]) {

        // Let's create a listing of meals which helps
        // to drop pounds, one of many prime concern programmers
        Listing<String> listOfFood = new ArrayList<>();
        listOfFood.add("Beans");
        listOfFood.add("Soup");
        listOfFood.add("Darkish Chocolate");
        listOfFood.add("Yogurt");
        listOfFood.add("Sausage");
        listOfFood.add("Pure Greens");
        listOfFood.add("Nuts");

        System.out.println("Unique ArrayList: " + listOfFood);

        // let's now reverse the listing in place in Java
        int dimension = listOfFood.dimension();
        for (int i = 0; i < dimension / 2; i++) {
            closing String meals = listOfFood.get(i);
            listOfFood.set(i, listOfFood.get(dimension - i - 1)); // swap
            listOfFood.set(dimension - i - 1, meals); // swap
        }

        System.out.println("Reversed ArrayList: " + listOfFood);
    }

}

Output:
Unique ArrayList: [Beans, Soup, Dark Chocolate, Yogurt, Sausage,
Pure Vegetables, Nuts]
Reversed ArrayList: [Nuts, Pure Vegetables, Sausage, Yogurt, Dark Chocolate,
Soup, Beans]

That is all about tips on how to reverse an ArrayList in place in Java. Simply take into account that you should use reverse ArrayList of any object e.g. String, Integer, Float, or Double. You may also use this algorithm to reverse Vector or every other Listing which helps index-based entry.

Another requirement of this algorithm is that Listing shouldn’t be unmodifiable i.e. set() methodology shouldn’t throw UnSupportedOperationException. Do not use this algorithm to reverse the linked listing in Java as a result of time complexity could be O(n^2), you possibly can see the next programs for extra particulars on calculating time and house complexity.

Hungry for Extra?? Right here you go

  • Easy methods to reverse a String in place in Java? (answer)
  • High 20 Amazon and Google Interview Questions? (listing)
  • Easy methods to implement the Quicksort algorithm in Java? [solution]
  • 7 Finest programs to study Knowledge Construction and Algorithms (programs)
  • Easy methods to discover all permutations of a String in Java? (answer)
  • Write a program to search out the highest two numbers from an integer array? [solution]
  • Easy methods to discover duplicate phrases in Java String? (answer)
  • 10+ Algorithms and Programming Programs to Crack Interviews (programs)
  • Easy methods to verify if an array accommodates a quantity in Java? [solution]
  • Easy methods to print the Fibonacci sequence with out recursion? (answer)
  • 10 Free Knowledge Construction and Algorithms Programs for novices (free programs)
  • Easy methods to discover the best and lowest factor within the unsorted array? [solution]
  • 10 Books to study Knowledge Construction and Algorithms (books)
  • Easy methods to verify if a String is a Palindrome in Java? (answer)
  • 10 Knowledge Construction and Programming Programs to Crack Interviews (programs)
  • Easy methods to discover duplicate components in an array? (answer)
  • 20+ binary tree questions from coding interviews (questions)
  • How do you print prime numbers as much as a given quantity? (answer)
  • 25 techniques design questions from interviews (questions)
  • Easy methods to discover the most important prime issue of a quantity in Java? (answer)
  • Easy methods to rely the variety of phrases in a given String? (answer)

Thanks for studying this text thus far. For those who like these dynamic programming coding issues then please share it with your pals and colleagues. When you have any questions or suggestions then please drop a
word.


P.S. – If you’re making ready for Programming Job Interview and also you want extra such questions, can verify the Knowledge Constructions and Algorithms Bootcamp by Jonathan Rasmusson course on  Udemy to refresh your information in fast time. 



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments