Monday, July 22, 2013

Optimize the cost of concatenation of all these strings into one big string.

You have n strings with their lengths. You are given an add(string s1,string s2) which would concatenate the string s2 with s1 and return s3. Optimize the cost of concatenation of all these strings into one big string.
Eg: 1,5,2 are the lengths of given strings.
1+5=6
6+2=8
total cost=14 can you Optimize this total cost?

Source : Sent by a reader named rahul.

Saturday, June 29, 2013

Print the objects of an array in the order of decreasing frequency. PS: Please make sure order of object should remain same

E.g. if array is of integer is given as  5 2 2 8 5 6 8 8, then we should get 8 8 8 5 5 2 2 6 , here freq. of 5 and 2 are same but 5 comes before 2 in array thus its should come before in output as well.

Here is the working code , let me know if it will fail for any test case and  if we can improve it?



/********************************************************
Time Complexity : O(n)+O(nlogn)+O(n)=O(nlogn)
Space Complexity : Auxallery Space O(2n)= O(n)
*********************************************************/
 Run Here http://ideone.com/FQ65xM

Wednesday, May 22, 2013

Given a sequence of n real numbers A(1) ... A(n), determine a contiguous subsequence A(i) ... A(j) for which the sum of elements in the subsequence is maximized


#include<stdio.h>
#define MAX(a,b) ((a>b)?(a):(b))
main()
{
  int arr[]={-2, -3, 4, -1, -2, 1, 5, -3};
  int len,i;
  int max=0;
  len = sizeof(arr)/sizeof(arr[0]);
  max=arr[0];
  int finalmax=0;
  int start=0,end=0;
  for(i=1;i<len;i++)
  {
    max = MAX(max+arr[i], arr[i]); 
      
        finalmax=MAX(max,finalmax);
    
  }
 
    
      printf("MAX:%d %d %d \n",finalmax, start ,end);
 
   
   
}
Example if you want to print array http://codepad.org/BhYxSlp4

Tuesday, March 19, 2013

How would you design a logging system for something like Google , you should be able to query for the number of times a URL was opened within two time frames.


i/p : start_time , end_time , URL1 
o/p : number of times URL1 was opened between start and end time.
Some specs : Database is not an optimal solution A URL might have been opened multiple times for given time stamp. A URL might have been opened a large number of times within two time stamps. start_time and end_time can be a month apart. time could be granular to a second.