Sort by

recency

|

572 Discussions

|

  • + 0 comments

    Java:

    Using bitwise operator will be time complexity of O(n) without requiring addition memory space.

    when we use xor between same number,

    7^7 = (0111)^(0111) -> 0^0 = 0, 1^1 = 0

    therefore,

    7^7 = 0000 -> its decimal value becomes zero

    conclusion: xor with same number provide zero.

    when we use xor between any value and zero,

    7^0 = (0111)^(0000) -> 0^0 = 0, 1^0 = 1

    therefore,

    7^0 = 0111 -> its decimal value becomes 7 (same number)

    conclusion: xor with a number provide the same number. No effect when we xor a value with zero

    Also, 7^4^7 is same as 7^7^4

    7^7^4 -> (7^7)^4 -> 0^4 (xor between same value is zero)

    0^4 -> 4 (xor a value with zero provides the same value)

    Now with more values,

    7^4^5^7^5 -> (7^7)^(5^5)^4 ->0^0^4 -> 4

    Since hackerrank gurantees only one unique element always there, so we can just use xor across the list and return the final output.

        // Write your code here
            int value = a.get(0);
            for(int i=1; i<a.size(); i++){
                value ^= a.get(i); 
            }
             
            return value;
        }
    
  • + 0 comments

    Perl:

    sub lonelyinteger {
        my $arr = shift;
        
        my %h;
        foreach (@$arr) {
            $h{$_} += 1;        
        }
        
        my ($tmp) = sort { $h{$a} <=> $h{$b} } keys %h;
    
        return $tmp;
    }
    
  • + 0 comments
    def lonelyinteger(a):
        # Write your code here
        result = 0
        for num in a:
            result ^= num
        return result
            
    
  • + 0 comments

    Here is my c++ solution, you can watch the vidéo explanation here : https://youtu.be/E4PVCUOdeXM

        int result = 0;
        for(int x: a) result ^= x;
        return result;
    }
    
  • + 0 comments

    hi yall