6

I am stuck in the following program:

I have an input integer array which has only one non duplicate number, say {1,1,3,2,3}. The output should show the non duplicate element i.e. 2.

So far I did the following:

public class Solution {

    public int singleNumber(int[] arr){
        int size = arr.length;
        int temp = 0;
        int result = 0;
        boolean flag = true;
        int[] arr1 = new int[size];

        for(int i=0;i<size;i++){
            temp = arr[i];
            for(int j=0;j<size;j++){
                if(temp == arr[j]){
                    if(i != j)
                    //System.out.println("Match found for "+temp);
                    flag = false;
                    break;
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {

        int[] a = {1,1,3,2,3};
        Solution sol = new Solution();

        System.out.println("SINGLE NUMBER : "+sol.singleNumber(a));
    }
}

Restricting the solution in array is preferable. Avoid using collections,maps.

8
  • The "cute" XOR-based solution could work... Commented Dec 31, 2014 at 13:49
  • Can you use another Array? if so I have a solution. Commented Dec 31, 2014 at 13:50
  • Is the array going to contain one and only one unique number? Commented Dec 31, 2014 at 13:51
  • @CoolGuy no but I think I found another solution, do the number to the power or 2, then take the original number and multiply it times each number, if it is ever equal to what is what when the number was taken to the power of two such as 3^2=9 and 3*3=9 then it is not unique and if no number is equal to the number then it is unique. Commented Dec 31, 2014 at 13:55
  • 1
    I think you can try using an HashMap to improve the performance. Commented Oct 21, 2015 at 15:49

12 Answers 12

12
public class NonRepeatingElement {

public static void main(String[] args) {

    int result =0;
    int []arr={3,4,5,3,4,5,6};
    for(int i:arr)
    {
        result ^=i;
    }

    System.out.println("Result is "+result);
}

}
Sign up to request clarification or add additional context in comments.

3 Comments

Please consider adding some explanation, not only raw code.
Here you have the explanation. algorithmsbyme.wordpress.com/2012/06/05/…
This solution doesn't work for negative numbers and zero. Also if there are odd number of repletions.
5

Since this is almost certainly a learning exercise, and because you are very close to completing it right, here are the things that you need to change to make it work:

  • Move the declaration of flag inside the outer loop - the flag needs to be set to true every iteration of the outer loop, and it is not used anywhere outside the outer loop.
  • Check the flag when the inner loop completes - if the flag remains true, you have found a unique number; return it.

3 Comments

Additionally, you could have your algorithm perfom a bit better if you start your inner "j" loop starting from i+1 instead of 0
@Joel If he does, the algorithm would return 1 on the second iteration of the outer loop, because there's no other duplicates for 1 when i is 1 and j is i+1 or more.
in some case for example {2,2,1} it will return result as 0 i think means if nique number has last slot in array than not sure, i think we need reset flag in inner condition
1
From Above here is the none duplicated example in Apple swift 2.0

func noneDuplicated(){    
            let arr = [1,4,3,7,3]    
                 let size = arr.count  
                 var temp = 0  
                 for i in 0..<size{  
                   var flag = true  
                   temp = arr[i]  
                     for j in 0..<size{  
                     if(temp == arr[j]){  
                        if(i != j){  
                            flag = false  
                            break  
                        }   
                    }   
                }    
                if(flag == true){   
                print(temp + " ,")   
                }  
            }  
        }

// output : 1 , 4 ,7
// this will print each none duplicated 

Comments

1
        /// for duplicate array 
        static void duplicateItem(int[] a){

                /*
                You can sort the array before you compare
                */

                int temp =0;
                for(int i=0; i<a.length;i++){
                    for(int j=0; j<a.length;j++){
                        if(a[i]<a[j]){
                            temp = a[i];
                            a[i] = a[j];
                            a[j] = temp;
                        }
                    }
                }

                int count=0;

                for(int j=0;j<a.length;j++) {

                    for(int k =j+1;k<a.length;k++) {

                        if(a[j] == a[k]) {

                            count++;
                        }

                    }


                    if(count==1){

                        System.out.println(a[j]);

                    }

                   count = 0;
                }

            }


    /* 

       for array of non duplicate elements in array just change int k=j+1; to int k = 0; in for loop

    */
    static void NonDuplicateItem(int[] a){

            /*
            You can sort the array before you compare
            */

            int temp =0;
            for(int i=0; i<a.length;i++){
                for(int j=0; j<a.length;j++){
                    if(a[i]<a[j]){
                        temp = a[i];
                        a[i] = a[j];
                        a[j] = temp;
                    }
                }
            }

            int count=0;

            for(int j=0;j<a.length;j++) {

                for(int k =0 ;k<a.length;k++) {

                    if(a[j] == a[k]) {

                        count++;
                    }

                }


                if(count==1){

                    System.out.println(a[j]);

                }

               count = 0;
            }

        }

public class DuplicateItem {
    public static void main (String []args){
        int[] a = {1,1,1,2,2,3,6,5,3,6,7,8};
        duplicateItem(a);
        NonDuplicateItem(a);
    }

Comments

1
    /// for first non repeating element in array ///
     static void FirstNonDuplicateItem(int[] a){

            /*
            You can sort the array before you compare
            */

            int temp =0;
            for(int i=0; i<a.length;i++){
                for(int j=0; j<a.length;j++){
                    if(a[i]<a[j]){
                        temp = a[i];
                        a[i] = a[j];
                        a[j] = temp;
                    }
                }
            }

            int count=0;

            for(int j=0;j<a.length;j++) {
                //int k;
                for(int k =0; k<a.length;k++) {

                    if(a[j] == a[k]) {

                        count++;
                    }

                }


                if(count==1){

                    System.out.println(a[j]);
                    break;

                }

              count = 0;
            }

        }

public class NonDuplicateItem {
    public static void main (String []args){
        int[] a = {1,1,1,2,2,3,6,5,3,6,7,8};
        FirstNonDuplicateItem(a);
    }

Comments

0

I have a unique answer, it basically takes the current number that you have in the outer for loop for the array and times it by itself (basically the number to the power of 2). Then it goes through and every time it sees the number isn't equal to double itself test if its at the end of the array for the inner for loop, it is then a unique number, where as if it ever find a number equal to itself it then skips to the end of the inner for loop since we already know after one the number is not unique.

public class Solution {

    public int singleNumber(int[] arr){
        int size = arr.length;
        int temp = 0;
        int result = 0;
        int temp2 = 0;
        int temp3 = 0;
        boolean flag = true;
        int[] arr1 = new int[size];

        for(int i=0;i<size;i++){
            temp = arr[i];
            temp2 = temp*temp;
            for(int j=0;j<size;j++){
                temp3 = temp*arr[j];
                if(temp2==temp3 && i!=j)
                    j=arr.length
                if(temp2 != temp3 && j==arr.length){
                    //System.out.println("Match found for "+temp);
                    flag = false;
                    result = temp;
                    break;
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {

        int[] a = {1,1,3,2,3};
        Solution sol = new Solution();

        System.out.println("SINGLE NUMBER : "+sol.singleNumber(a));
    }
}

Comments

0

not tested but should work

public class Solution {

    public int singleNumber(int[] arr){
        int size = arr.length;
        int temp = 0;
        int result = 0;
        boolean flag = true;
        int[] arr1 = new int[size];

        for(int i=0;i<size;i++){
            temp = arr[i];
            int count=0;
            for(int j=0;j<size;j++){
                if(temp == arr[j]){
                    count++;
                }
            }
            if (count==1){
               result=temp;
               break;
            }
        }
        return result;
    }

Comments

0

Try:

public class Answer{
   public static void main(String[] args) {
    int[] a = {1,1,3,2,3};
    int[] b =new int[a.length]; 
    //instead of a.length initialize it to maximum element value in a; to avoid
    //ArrayIndexOutOfBoundsException
    for(int i=0;i<a.length;i++){
      int x=a[i];
      b[x]++;
    }
     for(int i=0;i<b.length;i++){
       if(b[i]==1){
       System.out.println(i); // outputs 2
       break;
       }
     }
   }
}

PS: I'm really new to java i usually code in C.

4 Comments

If the array contains numbers bugger than a.length-1,your code will throw an ArrayOutOfBounds Exception
@CoolGuy, That's why I added a comment at line:4 of code.
Sorry. I haven't rad that comment when I was posting the comment. BTW,why don't you indent your code to make it more readable?
@CoolGuy, Thanks for suggestion, Done It. However I'm noob in editing So if you can edit that better than me, It'll be more acceptable.
0

Thanks @dasblinkenlight...followed your method

public class Solution {

    public int singleNumber(int[] arr){
        int size = arr.length;
        int temp = 0;
        int result = 0;

        int[] arr1 = new int[size];

        for(int i=0;i<size;i++){
            boolean flag = true;
            temp = arr[i];
            for(int j=0;j<size;j++){
                if(temp == arr[j]){
                    if(i != j){
//                  System.out.println("Match found for "+temp);
                    flag = false;
                    break;
                    }
                }

            }
            if(flag == true)
                result = temp;
        }
        return result;
    }

    public static void main(String[] args) {

        int[] a = {1,1,3,2,3};
        Solution sol = new Solution();
        System.out.println("SINGLE NUMBER : "+sol.singleNumber(a));
    }
}

One disastrous mistake was not enclosing the content of if(i != j) inside braces. Thanks all for your answers.

Comments

0

If you are coding for learning then you can solve it with still more efficiently.

  1. Sort the given array using merge sort of Quick Sort. Running time will be nlogn.
  2. The idea is to use Binary Search. Till required element found All elements have first occurrence at even index (0, 2, ..) and next occurrence at odd index (1, 3, …). After the required element have first occurrence at odd index and next occurrence at even index.

Using above observation you can solve :

a) Find the middle index, say ‘mid’.

b) If ‘mid’ is even, then compare arr[mid] and arr[mid + 1]. If both are same, then the required element after ‘mid’ else before mid.

c) If ‘mid’ is odd, then compare arr[mid] and arr[mid – 1]. If both are same, then the required element after ‘mid’ else before mid.

Comments

0

Another simple way to do so..

    public static void main(String[] art) {
    int a[] = { 11, 2, 3, 1,1, 6, 2, 5, 8, 3, 2, 11, 8, 4, 6 ,5};
    Arrays.sort(a);
    System.out.println(Arrays.toString(a));
    for (int j = 0; j < a.length; j++) {
        if(j==0) {
            if(a[j]!=a[j+1]) {
                System.out.println("The unique number is :"+a[j]);
            }
        }else
        if(j==a.length-1) {
            if(a[j]!=a[j-1]) {
                System.out.println("The unique number is :"+a[j]);
            }
        }else
        if(a[j]!=a[j+1] && a[j]!=a[j-1]) {
            System.out.println("The unique number is :"+a[j]);
        }
    }
}

Happy Coding..

Comments

0

Using multiple loops the time complexity is O(n^2), So the effective way to resolve this using HashMap which in the time complexity of O(n). Please find my answer below,

`public static int nonRepeatedNumber(int[] A) {

Map<Integer, Integer> countMap = new HashMap<>();
int result = -1;

for (int i : A) {
  if (!countMap.containsKey(i)) {
    countMap.put(i, 1);
  } else {
    countMap.put(i, countMap.get(i) + 1);
  }
}

Optional<Entry<Integer, Integer>> optionalEntry = countMap.entrySet().stream()
    .filter(e -> e.getValue() == 1).findFirst();

return optionalEntry.isPresent() ? optionalEntry.get().getKey() : -1;

} }`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.