Skip to main content

Posts

Showing posts with the label programming puzzle

[PUZZLE] Solve the following series

1, 20, 33, 400, 505, 660, 777, 8000, 9009, ........ Seems to be little strange ..huh. Most of times when i see this kind of series and i dont get a clue in couple of minutes, i become so mad with me. Fortunately today i could solve this in minutes. Here is explanation, sequence is Natural Number's binary representation * Number. Number  Binary  Binary * Number 1 1 1 2 10 20 3 11 33 4 100 400 5 101 505 6 110 660 7 111 777 8 1000 8000 9 1001 9009

Missing integer(s) in the array

You have given two array e.g. A[] and B[]. Difference between two arrays that A[] have two additional numbers than B[]. both the array is randomized and not in order.   We have to find out both the number in array A[] in most effcient way. Dont try to sort and compare as  time complexity is nlogn. Need a faster solution. Assume We have elements in array A are a0, a1, a2, ................an And Array B are b0, b1, b2, b3.....................bn. Now as per above condition all the elements of B  already  present with A. So we can represent like A[] = B[]+ai+aj where ai and aj is the missing number. Step1: XOR all the elements for A[] XOR B[]. So result will ai XOR aj as remaining elements will be removed by XOR.  Step2: Now take any bit set in above result. Assume we have result in variable result. Any bit set in result will be either set in ai or aj. Can not be in both the variable.  Assume set bit is 5th bit. A...

Least jump to reach array end

Given an array of Integers arr, from an element val = arr[i], you can go to element i to i+val. If val is zero, you cannot move forward. find the least selection to reach end of the array. example: 1 3 5 8 9 2 6 7 6 8 9 @index 0, can go to 1 @index 1, can go to 4. if index 3 and 4 choosen, it will reach to end frm there only. Give an algorithm and program. This can be solved with greedy aproach. Assume we are at index i, So For all i ..to i+a[i] index check for the max value value of k+a[k], where i We can prove the correctness of this . If k+a[k] having maximum value then any value except the k in range of i to i+a[i] will be less than range reachable by k. So by choosing k, you still can choose the option available with other indexs.

Merge two sorted array inplace

Given an integer array of which both first half and second half are sorted. Write a function to merge the two parts to create one single sorted array in place [do not use any extra space]. e.g. If input array is [1,3,6,8,-5,-2,3,8] It should be converted to: [-5,-2,1,3,3,6,8,8]

Permutations Sum(xi)

You have given "k" dice. How many way you can get a sum "S" and yes you have to throw all the dice. Write program for this. Its same permutations program...but we have to try with all the six S(1,2,3,4,5,6) possibilities for a dice. Exit condition will be If all the dice run out. SumP(dice,sum) = SumP(dice-1,sum-i)+i (from S).

All possiblities of balanced Parenthesis

print all balanced parenthesis of size "n". [ex:- for 1: (), for 2: ()(), (()); like this] Printing balance paranthesis, need dynamically updating your options. Such as initially only openeing brace can be choosen and closing braces are not present. You choose one opening brace and add into your result, this will decrease the number of opening brace but increase the closing brace count by one. In normal permuations program, we try with every element in set with every other element. So, here are only two choices given one opening brance and closing brace with n numbers. So, everytime we try to choose, we check for the opening brace count available and closing brance count available. I am posting my program here, #include using namespace std; static int permcnt; void print( char out[], int cnt) { //Print all the index from 0 to cnt-1 of out permcnt++; } void generate ( char in[], int i, int opara,int cpara) { int j; if ( opara == 0 && cpara == 0) { ...

Smallest Snip of givem M words

Yor are given occurrences of 3 words (say, "bangalore", "hyderabad", "google") in a file. bangalore: 100, 130, 157, ... hyderabad: 80, 145, 180, .... google: 60, 139, 197, ... [Note: occurrences are given in sorted order.] Now, you need to find the "smallest snip" containing all these three words. [In this case: 130("hyderabad"), 139("google"), 145("bangalore") - 15 is snippet size]. Can you generalize this for m words and length of occurrences is n. Algorithm: Take first element from all list and put in a array. minsnip = INT_MAX; while any of list have element. do currentsnip = max in array - min in array; if currentsnip minsnip = currentsnip; delete the min element from array. Get second element fron deleted list. done

Two numbers with minimum difference

Find the two numbers whose difference is minimum among the set of numbers. For example the sequence is 5, 13, 7, 0, 10, 20, 1, 15, 4, 19 The algorithm should return min diff = 20-19 = 1. Make an efficient algorithm, yeah best could be O(n). Not sure if i could use DP here, will post a solution tommorow. Let me know if you find a answer. Algorithm:MiniMumDiffN Get the size of array , say n. Get the range of array, range. Bucket Sort the above array. Search the above sorted array for minimum difference. This will be the minimum difference numbers. Now question comes where the range of above given array is very big. Algorithm:DivideArray Take an random element. Search for its position in array. Return the index of element. Algorithm:MiniMumDiff if array_range > MAXRANGE int mid = divideArray (arr,start,end); d1,max1 = MiniMumDiff( arr,start,mid-1); d2,max2 = MiniMumDIff(arr,mid+1,end); d3 = difference max1 and arr[mid] d4 = difference max2 and arr[mid] return minimum( d1,d2...

Largest Square, rectangular

you are given a M x N matrix with 0's and 1's find the matrix- 1. find the largest square matrix with all elements 1's 2. Find the largest rectangular matrix with all elements 1's Its simple DP problem guys ..just think of extending the solution to sub-problem. Will post answer soon..till then give it a try. Okie so recursive expression is SQ(i,j) = MIN(SQ(i-1,j),SQ(i-1,j-1),SQ(i,j-1))*ARR(i,j)+ARR(i,j); Idea is that SQ(i,j) will be a 1+ min of its precedents square size. I am multiplying and adding to avoid if else condition if ( ARR[i][j] == 1 ) SQ(i,j) = MIN(SQ(i-1,j),SQ(i-1,j-1),SQ(i,j-1))+1; else SQ(i,j) = 0; is same as this SQ(i,j) = MIN(SQ(i-1,j),SQ(i-1,j-1),SQ(i,j-1))*ARR(i,j)+ARR(i,j); Will post code soon.

Is Binary Tree?

Given a binary tree,write an algorithm to find if the tree is a binary search tree or not. Simple Recursive call is good.. int check_tree(bst *node) { if(!node) return TRUE; if(node->left!=NULL && node->info left)) return(false); if(node->right!=NULL && node->info right)) return(false); if(!check_tree(node->left) || !check_tree(node->right)) return(false); return(true); } I have already posted better algorithm in my tree sections earlier. Set Min and Max to INT_MIN and INT_MAX bool IsBst( node *root, int min, int max) { if (!root) return true; if ( !isBst( root->left,min,root->info) return false; if ( !isBst(root->right,root->info,max) return false; return true; }

Binary Matrix

For a binary matrix of size n x m of 0's and 1's. eg 1 0 0 1 0 0 1 0 0 0 0 0 If a location has 1; make all the elements of that row and column = 1. eg 1 1 1 1 1 1 1 1 1 0 1 1 Solution should be with Time complexity = O(n*m) and space complexity = O(1) Will post answer in comments. Try till then.

Median of stream of numbers

Problem: Design a data structure which can perform most efficiently insert and median. My Solution: struct node { int number; node *left; node *right; int leftTreeNode; }; struct header { int totalNodes; Int valid; int median; node *root; } myhead ; //myhead ......thats where it will start. void initialize() { valid = 0, median = 0, root =NULL, totalNodes =0; } void AddNode ( int n ) { myhead.totalNodes++; myhead.valid = 0; node *prev = NULL; node *temp = myhead->root; while ( temp != NULL ) { if ( n number ) { prev = temp; temp->leftTreeNodes +=1; temp = temp->left; } else { prev = temp; temp = temp->right; } } if ( prev != NULL ) { if ( n number ) prev->left = createNode(n) else prev->right = createNode(n); } else myhead->root = createNod...

Blood Relation

There are N persons in a country. N is very big in millions. Design a efficient data structure and algorithm to find out whether there is blood relations between given two person or say they have a common ancestor . My solution: Used a map //UID by Nandan Nilekani :) struct person { struct person *father; struct person *mother; list child; //However may not be needed for this problem string name ...i.e. //Add more } struct person * findAncestor ( struct person *a, struct person *b) { Take first node in stack. While ( stack is not null ) { Mark Node. Push Its ancestor in stack; } Take second node in stack. while ( stack is not null ) { If marked return Node, push ancestor in stack. } return NULL; } It has a drawback, i need to clear the flagged node before i apply the search algorithm again. But till now the best i know.

Maximum Gain Stock Market

Given an array which have samples of stock price at different timestamps. You have to find best timings when we can buy and sell and make maximum benifit by it. No need to say u can sell only after you buy. Its simple DP problem, just need to form a equation MaxGain(i) = Max(MaxGain(i-1), DIff(i,min)) Min is the index of element having min value till now. Diff will return the value(i)-value(min). Hope its clear.

Car Parking Problem

There is n parking slots and n-1 car already parked. Lets say car parked with initial arrangement and we want to make the car to be parked to some other arrangement. Lets say n = 5, inital = free, 3, 4, 1, 2 desired = 1, free, 2, 4 ,3 Give an algorithm with minimum steps needed to get desired arrangement. Told by one of my friend and after a lot of search i really got a nice solution. I will post solution in comment part

Median of Five Numbers

U have 5 NOs , X1,X2,X3,X4,X5 With minimum no. of comparisons we have to find a median. SWAP(X,Y) function is available to u . I have a answer of six comparisons and eight swaps....wait for people to find out by themselves.