Use a set or a boolean array to avoid double-counting duplicates. Here is some java code: /** * Do it! */ private void doit() { int n = sc.nextInt(); int k = sc.nextInt(); int count = 0; boolean used[] = new boolean[51]; Arrays.fill( used, false ); for( int i=0; i