Basic Algorithms: Round Robin List Elements | Circular Shift On a List in Apex

Telegram logo Join our Telegram Channel
Hello Trailblazers!!
Recently I came across a question on StackExchange and found it very interesting. So thought about sharing it on my blog.

So the Scenario is, assume we have a list of strings.
A, B, C, D

When we choose any of the element from the list we need to shift it and all elements after it to the start of the list. All elements before it need to add at the end of the list preserving their order.

If we choose B, the output should be B, C, D, A.
If we choose C, the output should be C, D, A, B.
If we choose D, the output should be D, A, B, C.
If we choose A, the output should be A, B, C, D.

Below is the solution for it:

public class RoundRobinList {
    public static List<String> perform(String choice, List<String> inputList){
        Integer ind = inputList.indexOf(choice);
        String[] outputList = new List<String>();
        if(ind > 0 ){
            for(Integer i=ind+1; i < inputList.size(); i++){

            for(Integer i=0; i < ind; i++){
            return outputList;
        return inputList;

Test cases:
List<String> inputList = new List<String>{ 'a', 'b', 'c', 'd'};
System.debug('Original List => ' + inputList);
System.debug('Input choice = b & OutputList => ' + RoundRobinList.perform('b', inputList));
System.debug('Input choice = c & OutputList => ' + RoundRobinList.perform('c', inputList));
System.debug('Input choice = d & OutputList => ' + RoundRobinList.perform('d', inputList));
System.debug('Input choice = a & OutputList => ' + RoundRobinList.perform('a', inputList));

Hope it helped you!
Happy Coding!!
No comments :
Post a Comment

Hi there, comments on this site are moderated, you might need to wait until your comment is published. Spam and promotions will be deleted. Sorry for the inconvenience but we have moderated the comments for the safety of this website users. If you have any concern, or if you are not able to comment for some reason, email us at