Sort by

recency

|

575 Discussions

|

  • + 0 comments

    Java using frequency map:

    public static int lonelyinteger(List<Integer> a) {
            if (a.size() == 1) return a.get(0);
            
            Map<Integer, Integer> map = new HashMap<>();
            
            for (int i : a) {
                map.put(i, map.getOrDefault(i, 0) + 1);
            }
    
            int result = 0;
            
            for (Map.Entry<Integer,Integer> e : map.entrySet()) {
                if (e.getValue() == 1) result = e.getKey();
            }
            
            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

    Does any one have knowledge about gratuity calculator qatar?

  • + 0 comments

    O(n)

  • + 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;
        }