id/email
password
forgot password | create account
about | help | code help+videos | done | prefs
CodingBat code practice

 

orion.a.smith@gmail.com apcsa-lists > apcsaListElementsToIndexes
prev  |  next  |  chance

Given an ArrayList of Integers, make passes forward through the list, moving any elements with values >=0 and < lst.size() into new index positions corresponding with their values. By "move," I mean remove them from their original location and insert them at a location such that, after removal/insertion is complete, the element is located at an index numbered the same as the element value. Keep doing this until a pass through the list either does not move any elements, or puts them back into an order indistinguishable from the order before the pass. Return the modified list.


For example, look at the third example input of [0, 1, 2, 3, 4, 0, 1, 2, 3, 4].  After one or more passes this will become [0, 1, 2, 3, 4, 0, 1, 2, 3, 4].  Processing through that will move the back half of the elements to the front of the ArrayList, but because of the repeated values the ArrayList looks the same after that pass as it did before the pass.  So, there's no need for an additional pass and we can stop processing.  This sounds like a good case for an outer while loop, since you really don't know how many passes you are going to end up making in advance.

Note that some numbers may repeat in the input!

apcsaListElementsToIndexes([0, 2, 1]) → [0, 1, 2]
apcsaListElementsToIndexes([3, 4, 5, 6, 7]) → [5, 6, 7, 3, 4]
apcsaListElementsToIndexes([0, 1, 2, 3, 4, 0, 1, 2, 3, 4]) → [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]

...Save, Compile, Run (ctrl-enter)

public ArrayList<Integer> apcsaListElementsToIndexes(ArrayList<Integer> lst) { }

Editor font size %:
Shorter output


Forget It! -- delete my code for this problem

Progress graphs:
 Your progress graph for this problem
 Random user progress graph for this problem
 Random Epic Progress Graph

Java Help

Misc Code Practice

Difficulty: 320

Copyright Nick Parlante 2017 - privacy