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.
Steps –

  1. Iterate step 2 to 5 until startIndex < endIndex
  2. store value at startIndex to temp
  3. replace value at startIndex with value at endIndex
  4. replace value at endIndex with temp
  5. increase startIndex by 1 and decrease endIndex by 1

Code –

Approach 2 : Using sublist of collection –
This could be done using Collections.reverse(List<?> list).
Steps –

  1. create empty list resultList.
  2. add sublist to resultList till startIndex excluding startIndex.
  3. get sublist from startIndex to endIndex including both. reverse it using Collections.reverse(List<?> list) and add to resultList;
  4. add remaining sublist resultList.

Code

Test Example – 

One response to “Reverse ArrayList Between 2 Given Indexes

  1. Magnificent items from you, man. I’ve keep in mind your stuff previous to and you’re just too
    magnificent. I really like what you have bought right here, certainly like what you’re saying and the way in which wherein you are saying it.

    You’re making it enjoyable and you still care for to keep it
    smart. I cant wait to read much more from
    you. That is really a wonderful website. https://En.Wikipedia.org/wiki/Gran_Canaria/074/5

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Bitnami