Tuesday, December 14, 2010

Rolling Indices

I am almost on my way back to home after attending Amritapuri regionals of ICPC. My team Proof has confirmed a berth in world finals to be held in Egypt 2011.

As promised I am going to revive this blog of mine. Though I don't have anything specific in mind, I plan to just discuss some cool tricks & problems which I find challenging. While I post stuff here, I expect all the readers to contribute too - in terms of problems and/or solutions.

I am today starting with a technique I call as Rolling Indices. 

Sample Problem :

You are given an array of numbers. You want to find if there are two numbers a,b in array such that a + b = S for some constant S.  If you don't know the technique yet, you may like to give this problem a little thought.

Naive Brute Force Solution :

Run over  three counters say i,j & check if A[i] + A[j] = S. This takes O(N^2) time & is clearly costly.

A better solution :

Sorting is cheap here compared to time we already have. But after sorting we can do a binary search. So just run over one counter say i & do a binary search for S - A[i]  in array. This takes time O ( N * log N) in sorting & same in processing. Little fast ! Fast enough yet ? No !

Rolling Indices technique :

Lets sort the array. & run on two indices say i & j ( yes these would be our rolling indices ) . We want to check as before if A[i] + A[j] = S or not. If A[i] + A[j] = S then you are really done. What if its not the case ? Maybe A[i] + A[j] > S. But pause here & ask yourself is this current value of i of any use at all ? All values of i & j you are going to consider hence after would give only a higher sum of A[i] + A[j] ( Array is sorted, remember ! ) which would not match S & so its no use to consider A[i] ever. Just forget this i & increment.

What if A[i] + A[j] < S  ? Simple. We have not yet considered all possibilities of i yet. Just increment j.

Analysis : We took O(N * log N ) time in sorting. Lets forget that & look at processing phase.  In each step we move i or j. We can't take more then 2 * N steps before we can't do anything . So processing is O(N)


This looks like an innocent & simple technique. In fact its as costly as binary search one with sorting being the bottle neck. But this was a sample problem just to introduce to concept of rolling ,  I can assure you that in "real" problems this is amazingly good. In particular sorted sequences arise naturally usually ( like prefix sums of positive numbered arrays ). Anycase tougher problems take more then N * log N time anyway so soring becomes cheap. Also this is trivially easy to implement & admits very neat & short code.

If you want to try more : try solving these :

1) Find if there are 3 indices i, j, k such that A[i] + A[j] = A[k] . Try for O(N^2).
2) You are given a rectangle with each entry being 0 or 1. Find if there is a sub matrix with sum exactly S. Try for O(N^3) algorithm.
3) If you really want an advanced problem try Hungry Bear from codechef.

I welcome any readers post any problem link or code for any problem solvable by this technique.

PS:
  • I realized only mid way , a post on prefix sums should ideally be there before this one . So give me some time & I should be posting on prefix sums soon.

Friday, August 27, 2010

String concatecation in java

So I came across a few articles claiming that string concatenation using + or (concat function is slower then using a buffered approach (StringBuffer or StringBuilder). I came across this post on the topic & ran the tests on my machine.
Results I got were something like this:
On avg concat was taking 4 sec & append was taking 1 ms. ( Number of iterations- 20000).

So I kept wondering why is it so slow really ? Is it because there is excessive copying or mutliple times space allocation ! So I modified Paul's code to add some extra testing function which you can find here at pastebin. Running the results on my & my friends machine gives very very different results:
               
                              Concat          Append         Alloc         Set Value
My machine          4000              2ms               800           80
Friends machine   8000              2ms               400           1200

Large differnce in concat times could possibly be explained due to speed of machines. But how one explains a fuzzy pattern ? We found later that he was on Java 1.6 & I was on java 1.5 . But then why would my setval function be so fast & his alloc be so slow ? What are the changes done behind the curtain ?


If anyone of you does the same test,(which is easy- copy the file & run it!) do log ur results & reply back to me...


Update: Also we thought about it later- I was on Linux & he was on windows. Is memory allocation dependent on OS too ?

Monday, August 9, 2010

P != NP !

Vinay Deolalikar, an extremely common & dull Indian name as such.
But that is what I would have said a few hours back on this name. What do I say now ? Well - this might well be the name of the most famous computer scientist of all times. Yes you read it right - of all times.

Why ? A guy with this name who works as a researcher  at HP labs, Palo Alto,  has claimed that he has a proof to establish that P!=NP.  What it means is that if this is true, not only he takes home 1 million $, THE most difficult & important problem of computer science would be solved .

His paper is awful 103 pages long & a preliminary version can be found here.This only brings one name to my mind- Andrew Wiles ! If you don't know why- well you don't deserve to be reading this blog !

You know what is startling ? This guy was not even a computer scientist. He was an electric engineering major from IITB only. Even his PhD was in electrical engineering. Though on his homepage, he describes himself as a mathematician.
It would be a long stick in the ass of all computer scientists of this world if an inter-disciplinary researcher solves the hardest nut.

Plus its cool that he was born & brought up in Delhi & he passed out of a university which is the nearest kin to mine.(IIT Delhi).
I am so excited.

Y0 baby. C0de monkey is jumping restlessly. :)

Tuesday, July 6, 2010

Raining Parabolas

Source: Spoj.pl
See the problem statement here

Problem: (In abstract) You have n length strip. You at any time choose a segment of strip [x0,x1] & apply paint on it such that paint applied on ith square is a*i^2 +b*i + c for constant a, b, c given with every paint trial.
Given any segment [x0,x1] we are to find the sum of paint amounts applied to this segment .

Constraints: We need an algorithm where both query for a given segment & updating a paint attemp take atmost O(logn) time.

Hunch: My first hunch is to go for segment trees ofcourse. What is problematic here is that sum amount to be applied is not uniform across all squares. I can think of only storing with each segment its total sum. So that query becomes O(logn) only. I dont know how to update yet.

Thursday, July 1, 2010

Tool Tips

Suddenly I feel so ahead of the groove- always current.
Like few days back I was working on new model of search & the next day I see exact same in (snapshots) of a web newssift.com ( dead now).  The other day I was seeing auto suggestion navigation lists & after I told Ayan what do I want it to look like- he shows me a recent page on something called Elastic List. I last week was thinking of auto suggest & now I see exact same functionality in facebook (ofcourse done before me thinking about it- but atleast I am starting to see & predict things my own.)

So what now ?
Tonight Only I saw a new feature in FB- you hover over some link & it loads you a tip box - sometimes a snapshot of the page too but essentially an html div . & I had spent all my day in finding the best way of doing a tool tip.


Here is a simplistic javascript tooltip creating code:


To actually create a tool tip , just bind this simple function to events like onhover or onclick & pass them proper arguements. You may also like to take measures to remove the div by using onmouseout or some other events.

Ofcourse this is too simple but possibilities are endless. Happy tool tipping. :)

Wednesday, June 30, 2010

jQuery

Fourth day of coding in java script & I have already written one fairly advanced app. Also today I started learning jQuery too. For javascript n00bs let me clarify- jQuery is the awsmest js library of this world written by another God John Resig.
jQuery  program I wrote today was - dynamic tab adder & remover in  arbitrary js container. I currently dont have functionality to support downloads through blogger but I hope to add it soon enough so I ll put for download all my work.

I have never found anything so exciting to codeup as whole javascript paradigm. I found my first ever dynamic scoped lanuage in js. What that means is :

If I have some variables in a program & user at run time enters a string say "totalSalary" , I can show him the contents of the variable "totalSalary". If you think this is trivial to do in your favorite static language- think again !

//TODO: 1) Creation of own home page in full javascript.
//TODO: 2) An auto suggest box

Thursday, May 20, 2010

Dominoes

Source: Spoj.pl

Problem: We have n sticks standing at some points on number line. Location & height of each are given . A single knock( to left or right) of some stick with knock all sticks which it touches. That is if a stick of height h at location h is knocked right , it will knock all sticks at x+1 , x+2....x+h.

Given all sticks' information , Find the minimum number of knocks required to knock all the sticks. We can only spend O(nlogn) time at max.


Link to exact problem page here.

Saturday, April 17, 2010

Adding Fractions

Source: CodeChef April Challange. See here

Problem: You have an array A of length n with each entry stroing a fraction a/b.
Define B[i] as length of sequence starting at i such that sum of fractions of this sequnce is largest amongst all sequnces beginning at i. Sum of a/b & c/d is defined to be (a+b)/(c+d).
Compute Array B given A.

Friday, April 16, 2010

LCM Sum

Source : CodeChef

Problem: Given n, calculate the sum LCM(1,n) + LCM(2,n) + .. + LCM(n,n), where LCM(i,n) denotes the Least Common Multiple of the integers i and n.

Update:  Solution given by a friend Tarundeep posted  in comments.

Sunday, March 28, 2010

Finding smallest cycle

The inspiration of this problem comes from an exam problem which I extended beyond limits of exams .

We are given a graph with edge weights which can be negative . There might be negative cycles as well in the graph. Given a vertex v, find the smallest simple cycle containing v.

Wednesday, March 10, 2010

Bin Packing ( Simplied Version )

Source : Problem from tutorial sheet of ADA ( course at IITD in algorithm design )

Problem : We are given n1 objects of type 1 with size s1 each , n2 of type 2 with size s2 each & n3 of type 3 with size s3 each. We have a large supply of bins each of size S. Find the minimum number of bind needed to pack all the objects. ( Obvly , Objects are not to be cut in fractions )

The begnning

This blog would be the place where I would be venting out my love for maths , algorithms , puzzles & programming. You are welcome to contribute. :)