Deleting three consecutive numbers in an array I am a beginner in programming, started about 2 months ago with Java, changing careers from law.

I have recently applied for an internship but was denied because I failed to do the pre-interview test right.

One of the tasks was to keep deleting 3 consecutive same integers from the array until the list is either empty or has no 3 consecutive same numbers. The assignment can be found here.

Below a description of the task with examples:


  Three brothers walk into a bar. All the beverages are placed in one
  line at the long bar table. The size of each glass is represented in
  an array of integers, glasses. The brothers will drink a round if they
  can find 3 consecutive glasses of the same size. The barman removes
  the empty glasses from the table immediately after each round. Find
  the maximum number of rounds the three brothers can drink.
  
  For glasses = [1, 1, 2, 3, 3, 3, 2, 2, 1, 1], the output should be
  brothersInTheBar(glasses) = 3. The brothers can start with a round of
  size 3, then after the glasses are cleared, a round of size 2 can be
  formed, followed by a round of size 1. One glass will be left at the
  table.
  
  For glasses = [1, 1, 2, 1, 2, 2, 1, 1], the output should be
  brothersInTheBar(glasses) = 0. There are no 3 consecutive glasses of
  the same size.


This is my code:

    public int brothersInTheBar(int[] glasses){

    if(glasses.length&lt;=2)
        return 0;

    ArrayList&lt;Integer&gt; glassesAsList = new ArrayList&lt;Integer&gt;();
    Arrays.stream(glasses).forEach(i -&gt; glassesAsList.add(i));

    int counter=0;
    for (int x=0;x&lt;glassesAsList.size()-2;++x){

        if(glassesAsList.get(x) == glassesAsList.get(x+1) &amp;&amp; glassesAsList.get(x) == glassesAsList.get(x+2)){
            glassesAsList.remove(x);
            glassesAsList.remove(x);
            glassesAsList.remove(x);
            counter++;
            x=-1;
        }
        if(glassesAsList.isEmpty())
            break;
    }
 return counter;
 }


I sent the email back asking what I did wrong, so I can improve in the future. The response from the company only said that I have to look more into algorithm complexity and that my code is inefficient.

So my question is how to improve my algorithm and what is wrong with it?
Remove(x) deletes the element and then shifts every element up so it alone is an O(n) operation making your entire algorithm O(n^2). I actually wrote a removeAtFast(x) which swaps the item being removed and the last element then removes the last element normally. But you can't do this because it messes up the ordering.

I'd create a new array like what Pure Evil suggested. Just go through the elements and if you find 3 consecutive numbers skip 3 ahead and continue copying.

Edit: Also it would appear your code would fail the first example given in the assignment.