Saturday, October 8, 2016

Verify if the given string is valid parentheses expression in c#

You are given a string with series for parentheses. The parentheses could be only of 3 opening parentheses {, (, [ and 3 closing parentheses }, ), ]. You need to figure out if the given input are valid expression or not. Valid mean if there is proper closing and opening parentheses.

Other details and algorithm can be found here. Below is the c# implementation.

http://www.geeksforgeeks.org/check-for-balanced-parentheses-in-an-expression/

Saturday, September 10, 2016

C# Implementation of Heap Sort

The code create the maxheap of the given array of size N and then swap the 0th index (max value) with the last index (N-1) and then again create maxheap with reduced array of size (N-1).

Continue this process unless complete array is sorted.


Thursday, March 17, 2016

Check if WMI class exist on machine through powershell

I was debugging a powershell which throw exception when it tries to GET the WMI class property of the class which does not exist on OS. I found that there are not simple example which explains the code to check the existence of wmi class and then query it property. Therefore i found a code snippet which works perfect for such scenario which check if class exists or not and then you can further query its property.


Example

if(Get-WmiObject -List | where { $_.Name -eq "Win32_PerfRawData_Counters_HyperVDynamicMemoryIntegrationService"})
{
          write-output "class exist"
}
else
{
          write-output "class do not exist"
}


I am checking the existence of wmi class "Win32_PerfRawData_Counters_HyperVDynamicMemoryIntegrationService".

On win2008 r2 / window7 and prev OS it does not exists therefore the code goes in else part.

On latest OS the if block get executed.

Wednesday, September 30, 2015

Rest vs Soap

I was reading the difference between REST and SOAP api and figured out why world is moving towards REST apis. I tried to write down few difference between them. I have also given links to few references as well.

http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm

Rest(Representational State Transfer )
Soap(Simple Object Access Protocol)
REST describes a set of architectural principles by which data can be transmitted over a standardized interface (such as HTTP)
SOAP defines a standard communication protocol.

The Web Services Description Language (WSDL) contains and describes the common set of rules to define the messages, bindings, operations and location of the Web service. WSDL is a sort of formal contract to define the interface that the Web service offers.
The W3C Technical Architecture Group (TAG) developed the REST architectural style in parallel with HTTP 1.1 of 1996-1999.
Microsoft introduced it.
REST is focused on accessing named resources through a single consistent interface
SOAP brings its own protocol and focuses on exposing pieces of application logic (not data) as services
Different data format XML/Json/CSV are supported.
SOAP supports XML
Rest reads can be cached
SOAP read cannot be cached.
While REST supports transactions, it isn’t as comprehensive and isn’t ACID compliant
WS-Security which adds some enterprise security features

Need ACID Transactions over a service, you’re going to need SOAP

SOAP has successful/retry logic built in and provides end-to-end reliability
Implementation is simpler. Beneficial for public apis. Easier to document and easier for end user/browser as well.

You can simply use browser for make a GET request. For other HTTP VERBS such as POST/PUT you can use various browser plugin and fiddler.

Advanced rest client chrome extension is my favorite.
SOAP is not as easier to code as compare to REST. Every time I ask my colleague that we need to implement a 3rd party API which is in SOAP he gives me weird look.
The RESTful Web services are completely stateless.


Session state is therefore kept entirely on the client. This constraint induces the properties of visibility, reliability, and scalability.

Visibility is improved because a monitoring system does not have to look beyond a single request datum in order to determine the full nature of the request.

Reliability is improved because it eases the task of recovering from partial failures.

Scalability is improved because not having to store state between requests allows the server component to quickly free resources, and further simplifies implementation because the server doesn’t have to manage resource usage across requests. Like most architectural choices, the stateless constraint reflects a design trade-off. The disadvantage is that it may decrease network performance by increasing the repetitive data (per-interaction overhead) sent in a series of requests, since that data cannot be left on the server in a shared context. In addition, placing the application state on the client-side reduces the server’s control over consistent application behavior, since the application becomes dependent on the correct implementation of semantics across multiple client versions


SOAP are stateful.


If a user attempts to upload something to a mobile app (say, an image to Instagram) and loses reception, REST allows the process to be retried without major interruption, once the user regains cell service.
If the SOAP service is interrupted it would require more initialization and state code.

The client context is stored on the server between requests which make initialization time consuming.

Monday, May 27, 2013

Stack and Queue Algorithm Questions


  1. Use single array to implement 3 stack.
  2. Implement stack class. Write push , pop and peek function. Write a function MIN which return minimum value in O(1).
  3. Implement queue using 2 stacks.


Sorting and Searching Algorithm Questions


  1. Given two sorted array A and B. A is large enough to hold B. Merge the arrays in sorted order.
  2. Write a function which sort the array of string such that 2 anagram are together.
  3. A array is sorted in increasing order and rotated many times. Find a number N in given array.
  4. You have 10 GB of file with each line having 1 string.Sort the file.
  5. Given sorted array of string. The empty string is inserted between each string. Find a given string in array.
  6. Given a matrix MxN which is sorted by row and column in increasing order. Find given element .

Tree and Graph Algorithm Questions


  1. Implement a function to check if binary tree is balanced. A balanced tree is whose left and right sub-tree height do not differ more than 1.
  2. Given a directed graph. Write algo to find route between 2 nodes.
  3. Given a sorted increasing order arrray. Create binary search tree with minimum height.
  4. Given a binary tree. Create a link list of all nodes at each depth.
  5. Write function which checks whether given binary tree is binary search tree.
  6. Write algo for next node "in order successor" of a given node in binary search tree.
  7. Write function of find common ancestor of 2 nodes. This may not be BST and avoid using other data structure.
  8. Given 2 very large binay tree. Find one tree is sub-tree of another at node N. So that if we cut tree at node N then both the tree are identical.
  9. Given the binary tree. Print all the paths whose sum is equal to gicen value. Path can start and end anywhere.

Algorithms learning resorces

MIT lectures
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-046j-introduction-to-algorithms-sma-5503-fall-2005/video-lectures/

Tuesday, April 2, 2013

Link List Algorithm Questions


  1. write a code to remove duplicates from unsorted link list. How would you solve it if temp buffer is not given.
  2. write algo to find nth to last element of singly link list.
  3. implement the algorithm to delete a node in the middle of a singly link list given only access to that node.
  4. write a algo to partition a linked list around a value such that all nodes less than x come before it and all nodes with value greater than x comes after it.
  5. suppose number are represented by singly linked list in reverse order. Eg . 123 is represented as       3->2->1. Write a function which could add these numbers and represent in link list.
  6. suppose number are represented by singly linked list in same order. Eg . 123 is represented as          1->2->3. Write a function which could add these numbers and represent in link list.
  7. Detect the loop in the link list. Also detect the loop node. Eg . a->b->c->d->e->b.   E is pointing to b so there is loop in link list.
  8. Implement a method to check if link list is palindrome.

Array Algorithm Question


  1.  Given an image represented by NxN matrix. Each pixel is represented by 4 bytes. Write a method to rotate image by 90 degree. Can you do in place ?
  2. Write an algo so that if an element in MxN matrix is 0 then entire row and column are set to 0.
  3. Given the array of integer. Find contiguous sequence of array with largest sum. Return sum and also calculate the start and end index of sub-array.
  4. Design algo to find pair of integer in a given array with specified sum.


String Algorithm Questions


  1.  Implement the algo to determine if a string has all unique characters. What is you cannot use additional data structure ?
  2. Implement the string reverse function.
  3. Given two string determine one is permutation of another.
  4. Implement the method to perform basic string compression techniques by using the count of repeated character. For example "aabbbccdddde" can be represented as "a2b3c2d4e1". If compressed string is not smaller than original string then return the original string.
  5. Write a code to check if string s1 is rotation of string s2.(eg. "hello" is rotation of "llohe" ). you have given method "substring" which check one word is substring of another. Use it only once to determine it.
  6. Calculate the occurrence of given word in a book.


Monday, March 11, 2013

Javascript Tutorial

http://www.scribd.com/doc/48750547/AJS

Nice presentation touches main concept of the language.


Saturday, March 9, 2013

Function Literal vs Function definition


Function Literal

var Class = function () {};
vs

Function Definition
function Class () {};


the former is "hoisted" to the top of the current scope before execution. For the latter, the variable declaration is hoisted, but not the assignment. For example:
// Error, fn is called before the function is assigned!
fn();
var fn = function () { alert("test!"); } 

// Works as expected: the fn2 declaration is hoisted above the call
fn2();
function fn2() { alert("test!"); }


http://stackoverflow.com/questions/4508313/advantages-of-using-prototype-vs-defining-methods-straight-in-the-constructor

Adding methods to a class vs adding methods to a class's prototype

https://www.quora.com/JavaScript/What-are-advantages-to-adding-methods-to-a-class-vs-adding-methods-to-a-classs-prototype

Snippet 1 (Adding methods to a class)

var myClass = function(prop1, prop2) {
    this.prop1 = prop1;
    this.prop2 = prop2;
    
    this.method1 = function() {//blah}
    this.method2 = function() {//blahblah}
}

Snippet 2 (Adding methods to a class's prototype)


var myClass = function(prop1, prop2) {
    this.prop1 = prop1;
    this.prop2 = prop2;
}
myClass.prototype.method1 = function() {//blah}
myClass.prototype.method2 = function() {//blahblah}


Snippet 1

  • Two functions are created for every construction of 
    myClass
  • can give you access to private variables and constructor arguments

Snippet 2


  • the two functions are created once: when the prototype is filled.
  • gives better memory usage
  • Methods that inherit via the prototype chain can be changed universally for all instances
  • For instance, you can extend the built-in String object by adding a trim function to it and all future instance of that object will share the trim function.

http://stackoverflow.com/questions/4508313/advantages-of-using-prototype-vs-defining-methods-straight-in-the-constructor

Sunday, July 29, 2012

Ten point everyone - ten commandants

1. We usually make mistake in things we are proficient in.
 2. Anything that can go wrong, will go wrong. (Murphy Law)
3. Never tell a lie for a mistake , accept it. (Universal Truth)
4. Don’t let yourself free, keep yourself busy in doing things. There are no free lunches.
5. You may not reap for your intelligence but you will be paid for your sincerity and hard work.
6. Don’t consider yourself over smart. People around you can be smarter than you.
7. In this fast life get some time for self-review (introspection).
8. Your conscience will tell you whenever you are doing wrong. Listen it carefully.
9. Remember that you are human being, not machine therefore act wisely. Your brain is 1 feet above your heart so use it first.
10. People above your hierarchy are usually smarter than you , so don’t fool them.

Tuesday, January 26, 2010

Republic day at Big Bazaar

This republic day we decided to shop at big bazaar for our regular grocery stuff completely unaware of what’s going on there? The big bazaar was celebrating 4 days of saving offer and 26th was the last day. The crowd at Big Bazaar can easily beat the Haridwar kumbh . People were flowing like water. The fear started to flow into our nerves as soon as we enter into Bazaar. There was no cart to place the stuff and buckets are always difficult to carry. Somehow we manage to arrange 2 bucket which could be utilized for our shopping. People were nudging each other and making their way. There was definite need of traffic policemen to control the human traffic. The situation was ideal for stampede and a single announcement of free stuff could have made it possible.

After buying couple of stuff we have decided to keep our buckets in a place and then bring other stuff to it instead of carrying it, as carrying them was more difficult than scoring a century in Perth. Someone also need to stand near it as there was also scarcity of bucket and the most expensive part is, in case it is hijacked then you need to again shop for things, which was next to impossible. As I was standing near our shopping buckets I got enough time to analyze different consumers. As Jan 26 was national holiday people have decided to bring whole family to Big Bazaar shopping because it was economical than taking them to other places. First time I realized that kids are no more over head to any trip and they could bring delight to your shopping. The parents have asked them to explore different items kept across the aisle and inform them. The kids were acting as spy in getting all the info and their movement were so swift (due to their size) that having more kids turned out to be the boon. The vitality of this information can be understood by the fact that a big bazaar worker asked me “Where is the Horlicks sir?”. Standing beside the chocolate shelf and as a responsible person I was arranging them as soon as a small nudge from deluge of persons made them fall. It kept me busy till the time my friend came after discovering Vim bar. Suddenly I heard the election campaign with loud speaker. I was surprise to know that Noida is still having some election pending. Soon I realized that this campaign is for shirt which was available at 999 for 3. A man was leading the campaign with a mic followed by person with placard describing the offer.

Another surprising fact was that the most common item bought was packets of aluminum foil. My sarcastic brain thought that are so much food is still packed from home? Then I soothe myself acknowledging the fact that men have also learnt to cook.

The climax was still left, the billing counter. As we Indian always believe in jugaad, so how we could be left behind here. As we have not forget to keep handkerchief to reserve our places similarly ambassador were sent earlier to reserve the billing slot so that they can save time while billing. The stuff were billed and kept adding by their fellow. Some have objected and others were mute spectator, but I was smiling murmuring "Happy Republic Day".

I don’t know whether we got some good stuff or saved some rupees while shopping at this place but definitely I could not justify the 3hr time of 2 engineers for this shopping. We have definitely paid more price than debit card swipe.

Friday, November 27, 2009

Love insurance

Series of incidents from few months have inspired me to pen down my thoughts. The haunting thought of people and their moral values frighten me. A young charming boy agrees for arrange marriage to soothe his parents, want to palliate his pre-marital gal frnd by fighting with his wife and alleviate himself from all responsibilities by suicide. The wife also follows the same step to assuage her pain. This is not a hypothetical story but an incident which came to me like a thunder bolt. Similarly there are plenty of incidents where people find it hard to decouple themselves from their past and their acts.
Looking from the eye of an entrepreneur I see a business opportunity here. What about love insurance? Like we have kidnap and ransom insurance in countries like Mexico , Venezuela and Nigeria where such crime are common someone can think abt luv insurance in India. I have chosen India because ours is the only country where you can bet on these values. The family system is so strong in our country that it has surpassed many recessions and depressions in which the richest economies like America and Britain collapsed. I am also hurt by the current trend which is precursor of deterioration of such values. I could see that 10 years from now people will start insuring their engagements and marriage. The company has to pay the victim insured amount for their break ups. The premium would be decided on the basis of risk involved so it is obvious that engagement would be having more premium than marriage. Premium will reduce to almost half amount once you are married and will again decrease further once you are blessed with a child. No premium has to be paid after age of 50 but you would continue to be insured under it.
Huh.. I am really disappointing while writing this. Who could think of that there would be price tag of your tears and emotions? Is I am seeing apocalypse in near future? This is very hard to describe. It is ‘I’ which is creating problem. It is ‘me’ which is causing turbulence, it is ‘mine’ which is reason for all agony. Nobody cares about ‘they’ ‘them’ or ‘theirs’.

Sunday, September 27, 2009

Importance of higher education in India

With recession round the corner, getting jobs is biggest nightmare in current scenario. Current slowdown has opened the pandora box and challenged the education system in India. If I could flashback period before 15-20 years ago, getting graduate degree from a college would open many new avenues for employment but now BA/BSc are far from even considered to be a degree and BE/BTech has replaced BA/BSc. There is hardly any guy who is ready to settle down for less than an engineering degree. Now this again raises the bigger question regarding employability of the candidate. Recent study says those more than 50 % of the engineers are unemployable. As per 2008 stats around 8 lakh engineers are graduating every year from approximately 2400 engineering college across the country. The irony of it all is that the engineering colleges which supposed to churn out professionals are actually getting reduced to degree vending machines producing largely good for nothing engineers.
Here is the time to seriously introspect ourselves and think about getting back the identity you lost among such large number of professional. The young Indian youth has come out of his comfort zone of mere job after graduation and started thinking for stability in future. Current recession was an eye opener which paved the way for higher education ME/MTech/MBA in India. The count of engineering graduates fighting for these courses has suddenly increased by leaps and bound. The coaching institutes have become active and one can easily see the spike in the count of students enrolling for these courses.

Hey students! What are you thinking now? It’s not about quantity but its quality which matters. We have progressed generation by generation. Our 10+2+3 education system has changed to 10+2+4 which will soon transform to 10+2+4+2, once every individual realize the power of higher education.
In the word of Aristotle “The roots of education are bitter, but the fruits are sweet”.

Thursday, July 23, 2009

Algorithm and puzzles

This space is for technical purpose. It would contain few questions and their solutions (in comments). The space is for my collection and if anyone wants to leverage this collection can use it. Any doubt and suggestions are most welcome.


  1. How would you calculate the square root of a number without any built in functions?

  2. Hints: You need to consider boundary conditions. It should be able to find square root of all integers including 0.

  3. To find the second max of an integer array.

  4. Hints: It should be done in O(n) complexity.

  5. You have 3 integer Arrays , say array A, array B and array C. You have to compare whether these arrays are equal, keeping in mind the following things:


    • All arrays are un-sorted

    • You cant sort the arrays individually before comparing them

    • Use optimized algo e.g. do not compare element by element


  6. You have an array A with 100 elements e.g. A[100]. It has got 60 elements in sorted order (Ascending) and 40 blank spaces.There is another array B, which has 40 elements e.g. B [40] and all of the are filled with values in sorted order (Ascending).Merge array B into array A, so that array A get its all elements filled and also gets sorted in ascending order, including new values from B. Restrictions are


    • You can't use third datastrusture of any kind for temporary storage

    • You can use some temporary variables

    • You can use simple merger sort algo.

    • Number of iterations and comparison have to be least possible.


  7. Given a large array of positive integers, we want to perform a large number of queries. Each query is as follow. For an arbitrary integer A, we want to know the first integer in the array which is greater than or equal A. A log(N) algorithm for each query is sufficient for this problem.



Sunday, June 21, 2009

BJP need a Bing touch

It was June 1, 2009 when a room packed by Microsoft pioneers waiting for launch of their new search (decision) engine. Being the part of this release I have seen redirect traffic going from 0 to 100 % that night and enjoyed every moment of it. The Microsoft has re-branded their LIVE search to Bing, the decision engine. The initial response is good and they are marching ahead in search arena which is undoubtedly dominant by Google. The rebranding has certainly helped them and given user a choice to Bing.

After being so close to this release along with keeping hawk eye on this 2009 election I was trying to create some analogy with my sane brain. The election was so well poised that 3rd front also dreamed for PM seat. The election which was marching towards hung parliament and none of them was near to majority ended with Congress forming govt quite comfortably. The Congress has not really gained the seats but their rival parties have lost them. The left has always being bottleneck to liberated thinking and BJP revolved around their old ideologies which caused them their seats. If we closely look at key blunder made by BJP then I could think of Varun Gandhi Pilibhit case, excessive attacking on Manmohan singh and Hindutva agenda. They have never decoupled themselves from Varun Gandhi so called doctored tape (I just read a news 30 min ago that forensic has given report that Varun’s hate speech CD was not doctored) where as Congress has revoked seat from Jagdish Tytler after opposition from Sikh community. The country which was badly hit by terrorism played safe by keeping BJP hard line agenda at bay. The BJP major vote bank was Indian middle class (as they were never able to penetrate villages) so called intellectual class which sideline themselves from hard line politics in period of global terrorism. BJP need to revisit their ideologies. They are still seen as bunch of extreme politicians painted by saffron brush. Though they are trying hard to fade this color but they are unable to disown it completely. The internal turmoil has popped up in recent BJP executive meeting held to post mortem the recent debacle in Lok sabha election. It clearly indicates that there is rift in party which needs to be sorted out. The country does need a strong and stable opposition which will impose few checks and measures on running government. BJP do need a man like Vajpayee to reunite and revive them. They have to brainstorm and derive more secular and liberal solution in this tough time. They need a sort of rebranding to get rid of their long imposed image of Hindu Party towards a party which keeps development as first priority.