To the question of removing each Kth element from an arraylist in a circle , an answer was proposed :
import java.util.ArrayList; public class MyClass { public static void main(String[] args) { ArrayList <Integer> list1 = new ArrayList(); int n = 10; int k = 3; for (int i = 0; i<n; i++){ list1.add(i+1); } int pos =0; while (list1.size()!=1) { pos = (pos+k-1)%list1.size(); list1.remove(pos); } System.out.print(list1.get(0)); } } This is a quadratic O (n²) algorithm, but apparently this is not obvious, since it leads to the following questions:
... where did you see n ^ 2 here? ... there is one while loop, which for each iteration "removes" one element, where is the square here?
How do popular Java implementations behave? Does the O (n) language specification guarantee behavior for ArrayList.remove(i) for an arbitrary index?
ArrayList.remove(i)is O (n) operation, which for this algorithm leads to O (n²):ntimes deleted one element (n*n). It remains only to find the link to the language specification where O (n) is explicitly guaranteed for ArrayList.remove () - jfs