![]() Here is our sample Java program to reverse an array in place, solution is simple and easy to follow, but don't forget to look at my JUnit tests to understand it a bit more. So now the requirement is clear, what approach comes to your mind? how do you solve this problem? You are also not allowed to use any open source library or Java API which can reverse the array directly like any method from class except Arrays.toString()to print arrays in Java. ![]() The key point to understand here is that you need to reverse the same array, you cannot use another array but one or two variables is fine. So now your task is to write a Java program to reverse an array in place.įor the sake of this problem, you can assume that it's an integer array (during the interview, you should ask these questions to your interviewer, because asking the right question to fill the gap in requirement is a trait of a good programmer and highly appreciated on both telephonic and face-to-face interviews). an array of 10 million orders and you don't have enough heap space available.Ĭan we make it better? Can we reverse an array in Java without using an additional buffer? Even If you encounter this question in your programming job interview, you will be surely asked to reverse the array in place, without using an additional buffer as an earlier solution takes a lot of space. You cannot use this solution if the array is big e.g. Boom!!, you have got an array that has elements in reverse order of the original array, but the problem is you have used an additional array here, which makes space complexity of your solution O(n). ![]() Reversing an array sounds pretty easy, isn't it? It does sound like that, because all you need to do is create an array of the same size, iterate through the original array from end to start, and populate your new array.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |