Popular Posts

Sunday, January 29, 2012

Find the 8digit number

Find a 8-digit number, where the first figure defines the count of zeros in this number, the second figure the count of numeral 1 in this number and so on....  


Start with 8 digit number, starting from left to right, 
first digit indicate number of 0's in 8 digit number, 
second digit indicate number of 1's in 8 digit number. 
Similary 7th digit indicate number of 7's in 8 digit number.


70000000 //8 digit number 7 indicate number of 0's in the number.
70000001 //As number of 7's = 1 so 7th place is 1
60000001 //As due to 1 on 7th place number of zeros = 6
60000010 //As 6 is present so 7th place, number of 6's = 1; number of 7's = 0
61000010 //As 1 is present on 7th place ; number of 1's = 1 so 2nd place there should be 1
51000010 //As number of 0's = 5 
51000100 //As 5 is present so 6th place is 1 number of 6's = 0; number of 7's = 0 
52000100 //As number of 1's = 2  
52100100 //As 2 is present on 1st place so 3rd place is 1
42100100 // As number of  0's = 4 so 1st place is 4
42101000 // As 4 is present so 5th place is 1; number of 5's, 6's and 7's = 0;
We got the answer as 4210 1000.


Source : http://anandtechblog.blogspot.com/2011/07/find-8digit-number-microsoft-interview.html

Saturday, January 28, 2012

What really happens when you navigate to a URL

As a software developer, you certainly have a high-level picture of how web apps work and what kinds of technologies are involved: the browser, HTTP, HTML, web server, request handlers, and so on.
In this article, we will take a deeper look at the sequence of events that take place when you visit a URL.

http://igoro.com/archive/what-really-happens-when-you-navigate-to-a-url/

Friday, January 27, 2012

Trim Binary Search Tree


Given the root of a binary search tree and 2 numbers min and max, trim the tree such that all the numbers in the new tree are between min and max (inclusive). The resulting tree should still be a valid binary search tree. So, if we get this tree as input:
and we’re given min value as 5 and max value as 13, then the resulting binary search tree should be:
We should remove all the nodes whose value is not between min and max. We can do this by performing a post-order traversal of the tree. We first process the left children, then right children, and finally the node itself. So we form the new tree bottom up, starting from the leaves towards the root. As a result while processing the node itself, both its left and right subtrees are valid trimmed binary search trees (may be NULL as well).

Find Next Palindrome Number

Given a number, find the next smallest palindrome larger than the number. For example if the number is 125, next smallest palindrome is 131.
Java program : 
public class NextPalindrome {
public static void main(String[] args) {
int n = 2133;

// temp variable to perform operations on n
int temp = n;
// calculate the number of digits
int digits = 0;
while (temp != 0) {
temp = temp / 10;
digits++;
}

// edge case if the given number contains all 9 s like 9 or 99 or 999
// or...,round off to next number
int divider = (int) Math.pow(10, digits);
if ((n + 1) % divider == 0) {
n = n + 1;
digits++;
}
if (digits == 0)
return;

// handling the special case of single digit numbers
if (digits == 1) {
System.out.println("Next higher palindrome is : " + n + 1);
return;
}

// create array of size digits to store the digits of the given number
int[] a = new int[digits];
temp = n;
for (int i = digits - 1; i >= 0 && temp != 0; i--) {
a[i] = temp % 10;
temp = temp / 10;
}

// now array contains the digits in same order as of number
int nextPalindrome = 0;
boolean isPalindrome = false;// used for track whether we got palindrome
// or not
while (!isPalindrome) {
// create mirror image of the given number
createMirrorImage(a);
nextPalindrome = constructNumber(a);
if (nextPalindrome <= n) {
int middle = (int) Math.ceil(digits / 2);
// if the middle digit is 9 then round off to the next higher
// number
if (digits % 2 == 0) {
if (a[digits / 2] == 9) {
a[middle] = 0;
a[middle - 1] = 0;
a[middle - 2] += 1;
} else {
a[middle] += 1;
a[middle - 1] += 1;
}
} else {
if (a[middle] == 9) {
a[middle] = 0;
a[middle - 1] = a[middle - 1] + 1;
} else {
a[middle] += 1;
}

}
} else {
isPalindrome = true;
}
}
System.out.println("Next higher palindrome is : " + nextPalindrome);
}

private static int constructNumber(int[] a) {
int num = 0;
for (int i = 0; i < a.length; i++) {
num = num * 10 + a[i];
}
return num;
}

private static void createMirrorImage(int[] a) {
int length = a.length;
for (int i = 0, j = length - 1; i <= j; i++, j--) {
a[j] = a[i];
}
}
}

Refer :  http://www.ardendertat.com/2011/12/01/programming-interview-questions-19-find-next-palindrome-number/

Median of integer stream

Given a stream of unsorted integers, find the median element in sorted order at any given time. So, we will be receiving a continuous stream of numbers in some random order and we don’t know the stream length in advance. Write a function that finds the median of the already received numbers efficiently at any time. We will be asked to find the median multiple times. Just to recall, median is the middle element in an odd length sorted array, and in the even case it’s the average of the middle elements.
Refer : 
http://www.ardendertat.com/2011/11/03/programming-interview-questions-13-median-of-integer-stream/

http://www.geeksforgeeks.org/archives/14873

Thursday, January 26, 2012

Missing element in an array


This question can be solved efficiently with a very clever trick. There is an array of non-negative integers. A second array is formed by shuffling the elements of the first array and deleting a random element. Given these two arrays, find which element is missing in the second array. Here is an example input, the first array is shuffled and the number 5 is removed to construct the second array.
Approach I :
The naive way to solve it is for every element in the second array, check whether it appears in the first array. Note that there may be duplicate elements in the arrays so we should pay special attention to it. The complexity of this approach is O(N^2). A more efficient solution is to sort the first array, so while checking whether an element in the first array appears in the second, we can do binary search. But we should still be careful about duplicate elements. The complexity is O(NlogN). If we don’t want to deal with the special case of duplicate numbers, we can sort both arrays and iterate over them simultaneously. Once two iterators have different values we can stop. The value of the first iterator is the missing element. This solution is also O(NlogN). 
Approach II :
We can use a hashtable and store the number of times each element appears in the second array. Then for each element in the first array we decrement its counter. Once hit an element with zero count that’s the missing element. The time complexity is optimal O(N) but the space complexity is also O(N), because of the hashtable. Ideally we would like to have constant space complexity.
Approach III : One possible solution is computing the sum of all the numbers in array1 and array2, and subtracting array2′s sum from array1′s sum. The difference is the missing number in array2. However, this approach is somewhat problematic. What if the arrays are too long, or the numbers are very large. Then overflow will occur while summing up the numbers.
Approach IV :  initialize a variable to 0, then XOR every element in the first and second arrays with that variable. In the end, the value of the variable is the result, missing element in array2.
Let’s analyze why this approach works. What happens when we XOR two numbers? We should think bitwise, instead of decimal. XORing a 4-bit number with 1011 would flip the first, third, and fourth bits of the number. XORing the result again with 1011 would flip those bits back to their original value. So, if we XOR a number two times with some number nothing will change. We can also XOR with multiple numbers and the order would not matter. For example, say we XOR the number n1 with n2, then XOR the result with n3, then XOR their result with n2, and then with n3. The final result would be the original number n1. Because every XOR operation flips some bits and when we XOR with the same number again, we flip those bits back. So the order of XOR operations is not important. If we XOR a number with some number an odd number of times, there will be no effect.
Above we XOR all the numbers in array1 and array2. All numbers in array2 also appear in array1, but there is an extra number in array1. So the effect of each XOR from array2 is being reset by the corresponding same number in array1 (remember that the order of XOR is not important). But we can’t reset the XOR of the extra number in array1, because it doesn’t appear in array2. So the result is as if we XOR 0 with that extra number, which is the number itself. Since XOR of a number with 0 is the number. Therefore, in the end we get the missing number in array2. The space complexity of this solution is constant O(1) since we only use one extra variable. Time complexity is O(N) because we perform a single pass from the arrays. 

Next higher number with the same digits


Given a number, find the next higher number using only the digits in the given number. For example if the given number is 1234, next higher number with same digits is 1243.
The naive approach is to generate the numbers with all digit permutations and sort them. Then find the given number in the sorted sequence and return the next number in sorted order as a result. The complexity of this approach is pretty high though, because of the permutation step involved. A given number N has logN+1 digits, so there are O(logN!) permutations. After generating the permutations, sorting them will require O(logN!loglogN!) operations. We can simplify this further, remember that O(logN!) is equivalent to O(NlogN). And O(loglogN!) is O(logN). So, the complexity is O(N(logN)^2).
Let’s visualize a better solution using an example, the given number is 12543 and the resulting next higher number should be 13245. We scan the digits of the given number starting from the tenths digit (which is 4 in our case) going towards left. At each iteration we check the right digit of the current digit we’re at, and if the value of right is greater than current we stop, otherwise we continue to left. So we start with current digit 4, right digit is 3, and 4>=3 so we continue. Now current digit is 5, right digit is 4, and 5>= 4, continue. Now current is 2, right is 5, but it’s not 2>=5, so we stop. The digit 2 is our pivot digit. From the digits to the right of 2, we find the smallest digit higher than 2, which is 3. This part is important, we should find the smallest higher digit for the resulting number to be precisely the next higher than original number. We swap this digit and the pivot digit, so the number becomes 13542. Pivot digit is now 3. We sort all the digits to the right of the pivot digit in increasing order, resulting in 13245. This is it, here’s the code:
 public static void main(String[] args) {
int n = 12543;

// Count the number of digits in the number
int numberOfDigits = 0;
int temp = (int) n;
while (temp != 0) {
temp = temp / 10;
numberOfDigits++;
}

// counting the number of digits is helpful in creating the array with
// enough memory
int[] a = new int[numberOfDigits];

int i = numberOfDigits;
while (n != 0) {// Storing the number in the array.
int digit = (int) n % 10;
n = n / 10;
a[--i] = digit;
}

// At each iteration we check the right digit of the current digit we’re
// at,
// and if the value of right is greater than current we stop, otherwise
// we continue to left.
for (i = numberOfDigits - 1; i > 0; i--) {
if (a[i] > a[i - 1]) {
break;
}
}

// Now i-1 will be the pivot element
// Find the minimum element from i-1 to end which is higher than element
// at position i-1
int minIndex = i - 1;
int minValue = a[i];
for (temp = i; temp < numberOfDigits; temp++) {
if (a[temp] < minValue && a[temp] > a[i - 1]) {
minValue = a[temp];
minIndex = temp;
}
}

// swap the both digits
temp = a[i - 1];
a[i - 1] = a[minIndex];
a[minIndex] = temp;

// now sort the digits from last position to i
countSort(a, i, numberOfDigits - 1);

// calculating the number from array elements
n = 0;
for (i = 0; i < numberOfDigits; i++) {
n = n * 10 + a[i];
}

System.out.println("Next higher number is : " + n);
}


Note that if the digits of the given number is monotonically increasing from right to left, like 43221 then we won’t perform any operations, which is what we want because this is the highest number obtainable from these digits. There’s no higher number, so we return the given number itself. The same case occurs when the number has only a single digit, like 7. We can’t form a different number since there’s only a single digit.
The complexity of this algorithm also depends on the number of digits, and the sorting part dominates. A given number N has logN+1 digits and in the worst case we’ll have to sort logN digits. Which happens when all digits are increasing from right to left except the leftmost digit, for example 1987. For sorting we don’t have to use comparison based algorithms such as quicksort, mergesort, or heapsort which are O(KlogK), where K is the number of elements to sort. Since we know that digits are always between 0 and 9, we can use counting sort, radix sort, or bucket sort which can work in linear time O(K). So the overall complexity of sorting logN digits will stay linear resulting in overall complexity O(logN). Which is optimal since we have to check each digit at least once.