In this post we will solve the Arrays-DS HackerRank Question
Problem Statement: We are given an array of integers like A[4,5,6] we need to reverse this array like A[6,5,4].
This question is easy and could have more than 1 solution . So probably we will not need much explanation but we will discuss different approaches in this post to get better understanding.
Data Set:
A=[10,4,1,6,9,3,2]
Expected Output:
[2,3,9,6,1,4,10]
Approach 1: Create new List and add the elements of the existing list in reverse order and return the new list.
public static List<Integer> reverseArray(List<Integer> a) {
List<Integer> reversedList=new ArrayList<>();
for(int i=a.size()-1;i>=0;i--){
reversedList.add(a.get(i));
}
return reversedList;
}
Input:
[1 ,22 ,23 ,57 ,67]
Output:
[67 ,57 ,23 ,22 ,1]
Note: Disadvantage of this Approach is that it will create a new list and occupy memory , so this solution will have O(n) space complexity.
Approach 2: Use the index of the elements and swap the elements of the list.
public static List<Integer> reverseArray(List<Integer> a) {
int startIndex = 0;
int endIndex = a.size() - 1;
while (startIndex < endIndex) {
int elementAtStartIndex = a.get(startIndex);
int elementAtEndIndex = a.get(endIndex);
a.set(startIndex, elementAtEndIndex);
a.set(endIndex, elementAtStartIndex);
startIndex++;
endIndex--;
}
return a;
}
Input:
[1 ,22 ,23 ,57 ,67]
Output:
[67 ,57 ,23 ,22 ,1]
Additionally we can also use Collections swap() method for swapping the values at a particular index instead of storing the values in local variables and assigning it at particular indexes.
public static List<Integer> reverseArray(List<Integer> a) {
int startIndex = 0;
int endIndex = a.size() - 1;
while (startIndex < endIndex) {
Collections.swap(a,startIndex,endIndex);
startIndex++;
endIndex--;
}
return a;
}
Input:
[1 ,22 ,23 ,57 ,67]
Output:
[67 ,57 ,23 ,22 ,1]
Or we can write our own basic swap function as well.
public static List<Integer> swapElements(List<Integer> list, int i, int j) {
int temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);
return list;
}
Finally its up to you what you have to use.
Output:
Please Let me Know, If you have any doubts.
Please Let me Know, If you have any doubts.