Store the indices
for ( int i = 0 ; i < n ; i ++ ) { Vector < Integer > v = new Vector < > ( ) ; v . add ( i ) ; if ( mp . containsKey ( arr [ i ] ) ) v . addAll ( mp . get ( arr [ i ] ) ) ; mp . put ( arr [ i ] , v ) ; }