As a part of the Java interview question paper I have got following issue to solve. But I am bit wonder whether how can I implement it without any Collection or intermediate
There is one method where you can use Math.abs. You should check for the sign positive.If it is positive then make it negative. If negative then that's the duplicated number or the repeated number. Example: A[] = {1, 1, 2, 3, 2} i=0; Check sign of A[abs(A[0])] which is A[1]. A[1] is positive, so make it negative. Array now becomes {1, -1, 2, 3, 2}
i=1; Check sign of A[abs(A[1])] which is A[1]. A[1] is negative, so A[1] is a repetition. Then just put all those repeated numbers into a list and print the size of the list.
The code in python is
from astropy.extern.ply.cpp import xrange
def printrepeat(arr):
print("The repeating elements are: ")
list =[]
for i in xrange(0,len(arr)):
ch = abs(arr[i])
if arr[ch] > 0:
arr[ch] = (-1)*arr[ch];
else: list.append(arr[ch])
print(len(list))
# driver code
arr = [1 , 3 , 2 , 2 , 1,3]
printrepeat(arr)
Solution 2: Taking 2 pointers
class Abc1{
public static void main(String[] args) {
int[] a = {1, 1, 2, 3, 2};
countDuplicates(a);
}
private static void countDuplicates(int[] a) {
int c = 0 ;
for(int i = 0 ; i < a.length ; i++) {
for(int j = i+1 ; j < a.length;j++) {
if(a[i] == a[j]) {c++ ;}
}//for
}//for1
System.out.println("dup => " + c);
}
}
Solution 3: HashSet
class Abc1{
public static void main(String[] args) {
String a = "Gini Gina Protijayi";
countDuplicates(a);
}
private static void countDuplicates(String aa) {
List list= new ArrayList<>();
Set set = new HashSet<>();
// remove all the whitespaces
String a = aa.replaceAll("\\s+","");
for( char ch : a.toCharArray()) {
if(!set.contains(ch)) {
set.add(ch);
}//if
else {if(!list.contains(ch) ) {list.add(ch);} }
}//for
System.out.println("number of duplicate characters in the string =>" + list.size());
System.out.println(list);
}
}
Solution:4(same concept as solution 1 but code is in Java)
import java.util.ArrayList;
import java.util.List;
public class AA {
public static void main(String[] args) {
int a[] = {4, 2, 4, 5, 2, 3, 1};
printRepeat(a);
}
private static void printRepeat(int[] a) {
List list = new ArrayList<>();
for (int i = 0; i < a.length; i++) {
if( a[Math.abs(a[i])] > 0) {
a[Math.abs(a[i])] = (-1)* a[Math.abs(a[i])] ;
}//if
else {
System.out.println( "Duplicate numbers => " + Math.abs(a[i]) );
list.add(Math.abs(a[i]));
System.out.println("list => " + list);
System.out.println("list.size() or the count of duplicates => " + list.size());
}//else
}//for
}//print
}