Reverse ArrayList Between 2 Given Indexes
Given an ArrayList and we need to reverse list from given startIndex to endIndex. example –
List – [1,2,3,4], startIndex = 1, endIndex = 3 result = [1,4,3,2]
List – [1,2,3,4,5], startIndex = 1, endIndex = 4 result = [1,5,4,3,2]
Approach 1 –
This approach starts swapping elements from startIndex and endIndex until startIndex is greater than or equals to endIndex. It’s complexity is O(n) with constant space complexity.
- Iterate step 2 to 5 until startIndex < endIndex
- store value at startIndex to temp
- replace value at startIndex with value at endIndex
- replace value at endIndex with temp
- increase startIndex by 1 and decrease endIndex by 1
Approach 2 : Using sublist of collection –
This could be done using Collections.reverse(List<?> list).
- create empty list resultList.
- add sublist to resultList till startIndex excluding startIndex.
- get sublist from startIndex to endIndex including both. reverse it using Collections.reverse(List<?> list) and add to resultList;
- add remaining sublist resultList.
Test Example –