Friday, May 5, 2017

Amazon Interview Question:Find the element that appears once in Java


 Question:  Find the element that appears once
 
   Input: arr[] = {12, 1, 12, 3, 12, 1, 1, 2, 3, 3}
   Output: 2

Explanation:

Given an array where every element occurs three times, except one element which occurs only once. Find the element that occurs once. Expected time complexity is O(n) and O(1) extra space.

Solution:



Before going to further discussion. first lets understand the XOR operation:

Lets see some XOR operation,

  1.   5 ^ 5     = 0101 ^ 0101 = 0000
  2.   1 ^ 1     = 0001 ^ 0001 = 0000
  3.   10 ^ 10 = 1010 ^ 1010 = 0000

From the above few operation, we can see that when a number is XOR with same number then result is 0.

Also XOR is Associative and Commutative, it means

Associative    = giving the same result regardless of grouping,

i.e. so that a*(b*c)=(a*b)*c

Commutative = independent of order;

as in e.g. "a x b = b x a"

1.  1 ^ 1 = 0
2.  1 ^ 1 ^ 2 ^ 2 = 0
3.  1 ^ 2 ^ 1 ^ 2 = 0

Irrespective of order, when a same number will be XOR twice then result will be 0.

We can use sorting to do it in O(nLogn) time. We can also use hashing, but the worst case time complexity of but hashing requires extra space.


The idea is to use bitwise operators for a solution that is O(n) time and uses O(1) extra space.
The solution is not easy like other XOR based solutions, because all elements appear odd number of times here. The idea is taken from here.

Run a loop for all elements in array. At the end of every iteration, maintain following two values.

ones: The bits that have appeared 1st time or 4th time or 7th time .. etc.

twos: The bits that have appeared 2nd time or 5th time or 8th time .. etc.

Finally, we return the value of ‘ones’

How to maintain the values of ‘ones’ and ‘twos’?

‘ones’ and ‘twos’ are initialized as 0.

For every new element in array, find out the common set bits in the new element and previous value of ‘ones’.
These common set bits are actually the bits that should be added to ‘twos’. So do bitwise OR of the common set bits with ‘twos’. ‘twos’ also gets some extra bits that appear third time. These extra bits are removed later.

Update ‘ones’ by doing XOR of new element with previous value of ‘ones’. There may be some bits which appear 3rd time. These extra bits are also removed later.

Both ‘ones’ and ‘twos’ contain those extra bits which appear 3rd time. Remove these extra bits by finding out common set bits in ‘ones’ and ‘twos’.

Sample Code:

import java.io.*;

class GFG
{
public static void main (String[] args)
{
int arr[] = {12, 1, 12, 3, 12, 1, 1, 2, 3, 3};
                 System.out.println(findElementThatAppearOnce(arr));
}

private static int findElementThatAppearOnce(int arr[])
{
  int result = 0;
  for (int i=0; i<arr.length; i++)
  {
   result = result ^ arr[i];
  }
  return result;
 }
}

Output:

12

Time Complexity: O(n)
Auxiliary Space: O(1)


No comments: