Showing posts with label interiview. Show all posts
Showing posts with label interiview. Show all posts

Thursday, September 15, 2011

Find the number occurred odd time in Array

Currently, I encountered a question in interview "find a number which occurred odd time in Array". Friends in fact the first you think answer by using Hashtable and iterating all the elements from list and counting the number of time the element occurs in list.

But if is you remenber the college days and XOR digital gate this is very simple question to answer.

if the 1 XOR 1 = 0 and 1 XOR 0 = 1 so if same number are bitwise XORed it will give 0 and if odd time EXORed gives the number it self.

for ie 1 XOR 1 = 0 but 1 XOR 1 XOR 1 = 1 so here is simple program to find single number which occurred odd time in array.


public class FindOddOccuranceInArray {

	public static void main(String[] arg) {
		int[] nums = new int[] { 1,2,2};
		int val = findOddOccur(nums);
		System.out.println("val :: " + val);
	}

	public static int findOddOccur(int[] nums) {
		int val = 0;
                // all even number will be XORed to 0 and even number will
                // remain
		for (int i = 0; i < nums.length; i++) {
			val ^= nums[i]; /bitwise xor
		}
		return val;
	}
}

Thursday, August 18, 2011

Welcome to Onsite Interview Blog

Friends,

There are occasion after onsite interview we want to share the questions asked during interview session. I would like to share some of the most difficult technical questions asked by the highly tech savvy companies like google, yahoo, salesforce and many others during onsite interview. We will discuss mostly in Java but the same questions may be applied other technical language. I would appreciate to join, discuss and share your interview questions and experience.