Search This Blog

Friday 27 February 2015

Segment Trees

As some of you might be knowing, Segment Trees are special type of data structure for query and updating of intervals of array in logarithmic time.Basically segment trees store data of specific intervals of array in tree form. The root contains the whole array, it’s left child contain data of start index to middle index and right child contain data of middle index +1 to end index and so on. So the leaf nodes contain data of specific element of array.
Now the data of element I have been mentioning can be anything like the sum of elements or the max element or the min element etc. I have written the code in java for data containing sum of elements. A segment tree for an array of n elements uses O(n log n) storage and can be built in O(n log n) time. Segment trees support searching for all the intervals that contain a query point in O(log n + k), k being the number of queried intervals.
The segment tree is stored in a form of heap so left child of node i is 2*i and right child of node i is 2*i+1. To build the segment tree for sum of particular range problem, I have recursively called the method for child nodes. The moment it is the leaf node, it will be the base case of the recursion so the parent will get the value of sum of its childrens values. In this way the whole tree will be created from bottom up.
private int[] treeNode;
private int maxsize;
private int height;

private final int STARTINDEX = 0;
private final int ENDINDEX;
private final int ROOT = 0;

public SegmentTree(int elements[])
{
  height = (int)(Math.ceil(Math.log(elements.length) / Math.log(2))); //height of segment tree is O(log(n))
  maxsize = 2 * (int) Math.pow(2, height) - 1;  //setting maxsize
  treeNode = new int[maxsize];
  ENDINDEX = elements.length - 1; //setting global variable to size of array given
  constructSegmentTree(elements, STARTINDEX, ENDINDEX, ROOT);  // calling method to construct tree from the array
}

private int getLeftChild(int pos){
   return 2 * pos + 1;
}

private int rightchild(int pos){
   return 2 * pos + 2;
}

private int constructSegmentTree(int[] elements, int startIndex, int endIndex, int current)
{
if (startIndex == endIndex) //base case or leaf node
{
   treeNode[current] = elements[startIndex];
   return treeNode[current];
}
int mid = (startIndex + (endIndex - startIndex) / 2);
treeNode[current] = constructSegmentTree(elements, startIndex, mid, getLeftChild(current))
+ constructSegmentTree(elements, mid + 1, endIndex, rightchild(current));
return treeNode[current];  // calling it recusively and setting the current node's value to sum of its children
}
Here’s the method to get result of query.
private int getSum(int startIndex, int endIndex, int queryStart, int queryEnd, int current)
{
if (queryStart <= startIndex && queryEnd >= endIndex )  // base case
   return treeNode[current];

if (endIndex < queryStart || startIndex > queryEnd)  // current node is out of range
   return 0;

int mid = (startIndex + (endIndex - startIndex) / 2);
return getSum(startIndex, mid, queryStart, queryEnd, getLeftChild(current))
+ getSum( mid + 1, endIndex, queryStart, queryEnd, rightchild(current));  //recursively calling the query method and getting the result
}

public int query(int queryStart, int queryEnd)
{
if(queryStart < 0 || queryEnd > treeNode.length)  // if the query is out of range
  return -1;

return getSum(STARTINDEX, ENDINDEX, queryStart, queryEnd, ROOT);
}
Here’s the code for updating the tree
private void updateTree(int startIndex, int endIndex, int updatePos, int update, int current)
{
if ( updatePos < startIndex || updatePos > endIndex) //update pos out of range
   return;
treeNode[current] = treeNode[current] + update;  // if current node comes under the range to update, update it first and then call the method on its children
if (startIndex != endIndex)
{
  int mid = (startIndex + (endIndex - startIndex) / 2);
  updateTree(startIndex, mid, updatePos, update, getLeftChild(current));
  updateTree(mid+1, endIndex, updatePos, update, rightchild(current));
}
}

public void update(int update, int updatePos, int[] elements)  // This method first calculates the diff to be added in each of the required nodes and then calls the method on the root of the tree
{
   int updatediff = update - elements[updatePos] ;
   elements[updatePos] = update;  //the elements of the array are updated first
   updateTree(STARTINDEX, ENDINDEX, updatePos, updatediff, ROOT);  
}
This is the test run
 public static void main(String args[])
     {
         int[] elements = {1,2,3,4,5,6,7,8,9};
         SegmentTree segmentTree = new SegmentTree(elements); //creating the segment tree
         int sum = segmentTree.query(1, 4);  //querying for sum of elements in range 1-4
  
         System.out.println("the sum is " + sum);
         segmentTree.update(3, 1,elements); // updating the tree
         sum = segmentTree.query(1, 4); //getting the updated result
         System.out.println("the sum is " + sum); 
     }   
And the output is
the sum is 14
the sum is 15
Segment tree stores cumulative values of all intervals of the array and each interval can be accessed in logarithmic time, segment tree can be very helpful for problems like range min or max or range sum which have large amount of queries.
Also if there is large amount of updates given in the problem the segment tree may not survive, for that lazy propagation comes in handy which I will discuss in my next blog.
Here is the link to 60 problems relating to segment trees,try them to get a hold of the topic
problems on segment trees

Learn to CODE?

How do I Learn to Code? This is probably the most nagging question at the back of your mind, once you have decided that you want to learn programming. Like learning anything else, there is no standard process for learning to code. Of course there are guidelines, there are courses, there are ideologies and there are set traditions, but there is no one single correct way.
One school of thought which is very popular and fairly simple to begin with isCompetitive Programming. Getting started with it is quite easy and if one devotes sufficient amount of time and effort, you can develop a very strong grasp of programming logic in relatively short amount of time.

Here are some steps to get started and be good at it.
  • Get comfortable writing code in either of one of these languages C, C++ or Java. Why only C, C++ or Java? Because these are the standard languages allowed in any programming competition.
  • If you are already good at C, it is suggested to learn C++. It is the most popular language among competitive programmers because of its speed and an excellent library in the form of STL (Standard Template Library).
  • Pick an online judge. Recommended ones are Topcoder and Codeforces. These sites have high quality of problems and also allow you to see other’s code post contest completion. These also categorize problems based on the topic. Some other popular judges include SPOJCodeChef (powered by SPOJ) andHackerEarth.
  • To begin with, start with simple problems that typically require transforming English to code and does not require any knowledge on algorithms. Solving Div 2 250 (Division 2, 250 points) in Topcoder or Div 2 Problem A in Codeforces is a good start.
  • At the early stages of programming one tends to write long pieces of code, which is actually not required. Try to keep codes short and simple.
  • Practice these problems until you become comfortable that you can submit it for 240 odd points on any day.
  • Start implementing basic(or standard) algorithms. It is suggested to read them from Topcoder tutorials orIntroduction to algorithms.

Some basic concepts that you should learn are
  1. Graph algorithms: Breadth first search(BFS), Depth first search(DFS), Strongly connected components(SCC), Dijkstra, Floyd-Warshall, Minimum spanning tree(MST), Topological sort.
  2. Dynamic programming: Standard dynamic programming problems such as Rod Cutting, Knapsack, Matrix chain multiplication etc.
  3. Number theory: Modular arithmetic, Fermat’s theorem, Chinese remainder theorem(CRT), Euclidian method for GCD, Logarithmic Exponentiation, Sieve of Eratosthenes, Euler’s totient function.
  4. Greedy: Standard problems such as Activity selection.
  5. Search techniques: Binary search, Ternary search and Meet in the middle.
  6. Data structures (Basic): Stacks, Queues, Trees and Heaps.
  7. Data structures (Advanced): Trie, Segment trees, Fenwick tree or Binary indexed tree(BIT), Disjoint data structures.
  8. Strings: Knuth Morris Pratt(KMP), Z algorithm, Suffix arrays/Suffix trees. These are bit advanced algorithms.
  9. Computational geometry: Graham-Scan for convex hull, Line sweep.
  10. Game theory: Basic principles of Nim game, Grundy numbers, Sprague-Grundy theorem.
The list is not complete but these are the ones that you encounter very frequently in the contests. There are other algorithms but are required very rarely in the contests.
You can find description and implementation of standard algorithms here.
  • Once you have sufficient knowledge of popular algorithms, you can start solving the medium level problems. That is Div 2 all problems in Topcoder and Codeforces. It is advisable not to go for Div 1 500 at this point.
  • Learning to code is all about practicing. Participate regularly in the programming contests. Solve the ones that you cannot solve in the contest, after the contest. Apart from Topcoder and Codeforces you can also look at HackerEarth Challenges or Codechef contests.
  • Read the codes of high rated programmers. Compare your solution with them. You can observe that it is simple and shorter than your solution. Analyse how they have approached and improve your implementation skills.
  • Read the editorials after the contest. You can learn how to solve the problems that you were not able to solve in the contest and learn alternative ways to solve the problems which you could solve.
  • Always practice the problems that you could solve in the contest. Suppose if you are able to solve Div 2 250 and 500 in the contest but not Div 2 1000 then practice as many Div 2 1000 problems as as you can.
  • Do not spend too much time if you are not getting the solution or are stuck somewhere.
  • After you feel that you have spent enough time, look at the editorials. Understand the algorithm and code it. Do not look at the actual solution before you have attempted to write the code on your own.
  • Programming is a very practical and hands on skill. You have to continuously do it to be good at it. It’s not enough to solve the problem theoretically, you have to code it and get the solution accepted. Knowing which algorithm/logic to use and implementing it are two different things. It takes both to be good at programming.
  • Programming learning phase is going to take a lot of time and the key ispracticing regularly. It takes some time before you can attempt Div 1 500 and other tough problems. Do not give up on reading the editorials and implementing them, even if it takes many hours/days. Remember everything requires practice to master it.
It takes considerable amount of time before you get good at it. You have to keep yourself motivated throughout. Forming a team and practicing is a good choice. Not giving up is the key here.

Amazon interview experience of a student of DA-IICT




Round 1: (MCQ’s and 2 coding questions)

An online test was conducted consisting of 20 MCQ’s and 2 coding questions. MCQ’s consisted of data structures, OS and DBMS concepts. They were quite easy. 2 coding questions were:
  1. Given a linked list where every node represents a head of another linked list and contains two pointers of its type (all linked list are sorted). First, Pointer to next node in the main list and Second, Pointer to a linked list where this node is head.Write flatten function to flatten the lists into a single sorted linked list.
  2. Print vertical sum of all the axis in the given binary tree.

Round 2: (F2F Interview)

Given number N<10^7  and 0=<K<=9  (a digit).Find the total number of occurrences of K from 1 to N. Example N=11 and K=1 then ans=4. I was asked to write the code.I solved it in complexity of O(number of digits in N) using DP.

Round 3: (F2F Interview)

  1. Given a binary tree to be passed through a network. How to pass this tree in minimum space.It was an open ended question and he asked me for many solutions and finally asked me to write the code.
  2. Given two sorted list, find the Kth largest element from the combined sorted list.

Round 4: (F2F Interview)

  1. Given array of integers, find 1st non repeating element and write code.
  2. He asked me some Operating system question- what is difference between malloc and declaring an array, what is memory leak, garbage collection, main difference between C and C++ related to Memory allocation. There were some more, I am not able to recall all of them.
  3. Given N, find total number of Zeros at the end of N!. (of course with proof).
  4. Given a linked list with every node containing two pointers next and random. next points to next element and random points to any random element in linked list. Create a copy of this list. He asked me to write the code.

Round 5: (F2F Interview with manager)

  1. Discussion about only one of my projects. More than technicality of project he concentrated on my role in project, Teamwork, idea etc.
  2. OS concepts like difference between threads and process.
  3. Given that main memory is very cheap,what is need of virtual memory.
  4. Cryptography concepts like what is difference between hashing data and encrypting data. What are different types of encryption schemes.
  5. Given a binary tree and a SUM, print all the path from root whose sum = SUM.
  6. He asked me the same question-: Given a binary tree to be passed through a network. How to pass this tree in minimum space. So, he just asked me discuss the approach.
  7. Given a sorted array (elements may or may not repeat) and number Find the starting and ending index of X in array. if X is not present in array return -1,-1. He asked me to write code.
All F2F round took around 1 hr and 15 mins.
Finally after a long long wait of 7 hours I was hired along with my 3 colleagues ...!!!

Flipkart Interview Experience of a Student of DA-IICT

Coding Round

First round was coding round which had two questions on interviewstreet and lasted for 1.5 hrs. Here are the questions:
  1. We are required to transport a package using trucks. We are given package size and trucksize (every truck has equal capacity). The package can be repeatedly broken into half i.e 6 cn be broker into 3-3 and 3 can be boker into 1-2. We were required to code a program which could tell the minimum amount of trucks required for given packagesize and trucksize.
  2. We are given 4 type of infinite coins. We are given value of each time. We were required to tell whether we can pay someone using these coins.

Machine Round

After coding round 50 students out of approximately 300 were selected. Then we had a 2 hr  machine coding round. In this round, a question on binary tree was given. We were required to code a lot of functionality, like finding least common ancestor etc. Following was the criteria of judging:
  1. Compilation of code
  2. Number of test cases that it passed
  3. Algorithm/Logic
  4. Code readability
I felt that the code for the problem was lengthy but was simple. Many panicked after reading the question and functionality that we were required to implement. So for this round I would advise you to code on sites like codechef, codeforces so that you can code your logic well. Also I think practicing from DSA lab questions would help a lot. Main part is to get your code to compile, as they graded only those codes which compiled. Second thing is that it might not be necessary that your code passes all test cases because if your code compiles, passes most of the test cases and if the logic is good, then you can get into the next round. I am stating this because as far as I know, only mine and Shashank Parekh’s code passed all test cases but other 13 people who got selected had their code compiled properly and were able to pass most of the test cases, and most importantly had good logic regarding problems.

Technical PI

In this round one SDE from flipkart conducted the PI. He asked two questions:
  1. Zig Zag traversal of tree
  2. Data Structure for job scheduling. The jobs had only start time and arrival time. I was able to provide a O(logn) and he seemed happy with it.

HR PI

6 people were selected for this round. An Engineering Manager took our interview. The questions were aimed at testing your personality. The questions were like why flipkart?, state one of thing you have done that you are proud of. Also, in the conversation I mentioned that I liked Digital Image Processing, so he asked me algo to segregate a particular shape. In the end 4 people were selected for the role of SDE.
I felt that process was quite easy as compared to amazon but still coding round and machine coding round tested your ability to code fast. Also, the difficulty level of the questions that were asked in technical PI was random, so if you are good at coding then only you can be sure of making it to flipkart!

What is GSoC? (Google Summer Of Code)

Hello everyone. Firstly, let me quickly introduce myself. My name is Shourya Singh Gupta and last year I did my GSoC with digiKam on this project. In this blog I will be giving some tips to get selected for GSoC. This will be helpful to those guys who are going to try to participate in GSoC this year and in the upcoming years.
If you are reading this blog, then probably you are already aware of what GSoC is. But if not, I will give a very short info about what GSoC is. The Google Summer of Code is an annual program in which Google awards stipends (of US$5,500, as of 2014) to all students who successfully complete a requested free and open source software coding project during the summer. The program invites students who meet their eligibility criteria to post applications that detail the software-coding project they wish to perform. These applications are then evaluated by the corresponding mentoring organization. Every participating organization must provide mentors for each of the project ideas received, if the organization is of the opinion that the project would benefit from them. The mentors then rank the applications and decide among themselves which proposals to accept.
Now having given a summary of GSoC, lets get back to the main problem and that is,“how to do it ?”. So the first step towards participating in GSoC and a very crucial one I suppose is selecting an organization to work with. For this you can open last year’s website of GSoC and look for organizations that require the same skill set that you possess. Here when comparing your skill set with that required by the org, its best if you have all the skills that is required by the org, but in case you have most of the skills and not all of them then do not just rule out that org. If you think you can quickly acquire those remaining skills before starting to contribute in the org, then do take that org into consideration. This is actually one of those phases in GSoC where you get to learn those tools and technologies that you do not know yet. Now after you have shortlisted the organizations that require the same skill set that you possess, its time to select that one org in which you are going to contribute and hopefully do your GSoC with. Here different people have different views, some say its better to keep contributing in different organizations because that increases your chance to getting selected in GSoC, but I personally believe that its better to channelize your entire energy into working with one org rather than trying your hands on too many things. So do not try be jack of many rather be a master of one. One more thing that you could keep in mind while finalizing your org is to check whether that org is a regular participant in GSoC or not. Some organizations are not regular participants in GSoC. So if you want to play it safe, try to choose an org that has been regularly participating in GSoC since past few years.
After having selected the org, its time to move to the second step. Now you need to download the code base of the software that you need to work on and build and install it. I am explicitly mentioning this because if the procedure to build and install your software is complex you might get various unresolved dependency errors which takes a little while to solve. I have seen people quit preparing for GSoC because they were stuck for a long time in this step and got frustated. So if you are stuck somewhere do not get disheartened. Keep trying. If you are really not able to solve it, you can also ask the lead developers of the software about how to solve the problem. They will surely help you out.
Having done this, its time to move to the third step, which is solving bugs in software and establishing a good rapport with the lead developers(your potential GSoC mentors) of the software. This is actually the step that will determine to a great extent whether you will be selected or not. So firstly, join IRC/mailing list of the software on which you are working. This will be the medium of communication between you and the lead developers of the software. You need to prove to those guys that you have the potential to successfully complete the GSoC project if its assigned to you and the best way to prove this is by fixing bugs in software. The more bugs you solve, the more confident they get about you. Also, if you get stuck somewhere while solving a bug then do not hesitate to ask them. They are not going to think that you are a fool or anything. They understand that it takes time for a beginner to get accustomed to a large code base. But ask intelligent doubts. Do your own research before asking any doubt.
By Feb end or 1st week of March, you should choose a project on which you would like to work on, from the list of ideas proposed by the organization. This is the fourth step.You need to discuss in great depth the technical details of the project with your mentor and then you need to write a proposal stating how you are going to work on this project and the timeline that you are going to follow. You should really know the details of the project in and out. This not only improves the standard of proposal you write but in fact helps you a lot when you are are actually coding in the summer for your project.
Now the fifth step is to simply sit back and relax till the results are announced  . Whether you get selected or not is another story. I think you should be proud of yourself if you have even come this far. I am pretty sure you might have gained a lot of experience by this time, which will be of great use to you. And if you are selected, then Congratulations !!! I can guarantee you one thing, seeing your name, after working so hard for it, in the list of selected students will be one of the best moments of your life. And if that’s not enough for you, you are going to get $5,500 in the next few months (I guess that’s good enough reason for any person to be overwhelmed with happiness plus a t-shirt and some cool goodies.
And lastly just a word of caution. Please do not make the mistake of not working on your project after getting selected for GSoC. There will 2 evaluations during the coding period and you need to pass both the evaluations to get the certificate of completion and the total $5,500.
So best of luck to all the aspirants !!
May the force be with you !! 

Monday 23 February 2015

Top 16 jQuery Interview Questions Answers for JavaScript Programmers

Without a doubt, jQuery has given a much needed boost to JavaScript, a language so useful but equally underrated at times. Before jQuery comes into picture, we used to write lengthy JavaScript code not just for bigger but even for smaller functionality. Those code were at times both difficult to read and maintain. Having written JavaScript before using this excellent library, I realized true power of jQuery, just after using it for a month. Given it's huge popularity, jQuery interview questions are increasingly asked in any web developer interview, not just beginners but also experienced developers, including HTML and JavaScript. Since jQuery is relatively new, most interview questions are asked from core jQuery library including selectors, DOM manipulation and jQuery basics. In this article, I am sharing a list of 16 jQuery questions asked to HTML and JavaScript programmers in different interviews. Some of this questions also asked in Java Web development interview, where it's required to work on both Server side (Spring, Servlet and JSP) and Client side (HTML, CSS, JavaScript and jQuery). If you are going for an interview, where role demands multiple skills e.g. Java, jQuery, it's not expected from you to know every minor detail or comprehensive knowledge of jQuery, but if you are going for a purely client side development role, you might get more tricky and advanced jQuery questions than mentioned in this article. Nevertheless, you can use it to quickly revise some of the most frequently asked jQuery questions on interviews, but they are mostly suited for web developers with 2 to 5 years of experience, especially in Java stack.




jQuery Interview Questions and Answers

JavaScript is a standard for client side scripting and jQuery makes writing JavaScript much easier. You can achieve a lot more by just writing couple of lines of jQuery code. It is one of the most used JavaScript library and there is hardly any new project, which is using plain JavaScript without jQuery. What this means to you, a Java web developer is that you will bound to see couple of jQuery interview questions in Java web development interviews. Earlier it was mostly HTTP, HTML, CSS and JavaScript but now days apart from JavaScript fundamentals, people like to know whether you are familiar with jQuery or not. This list of 16 jQuery questions is prepared for web developers and can be very handy to revise key concept before telephonic or screening round of interview. If you are new to jQuery then it will also help you to understand fundamentals better and inspire you to explore more.


1. What is $() in jQuery library? (answer)

The $() function is an alias of jQuery() function, at first it looks weird and makes jQuery code cryptic, but once you get used to it, you will love it's brevity. $() function is used to wrap any object into jQuery object, which then allows you to call various method defined jQuery object. You can even pass a selector string to $() function, and it will return jQuery object containing an array of all matched DOM elements. I have seen this jQuery asked several times, despite it's quite basic, it is used to differentiate between developer who knows jQuery or not.



2. You have five <div> element in your page? How do you select them using jQuery? (answer)

Another fundamental jQuery question based on selector. jQuery supports different kinds of selector e.g. ID selector, class selector and tag selector. Since in this question nothing has been mentioned about ID and class, you can use tag selector to select all div elements.  jQuery code : $("div"), will return a jQuery object contain all five div tags.  For more detailed answer, see the article.



3. Difference between ID selector and class selector in jQuery? (answer)

If you have used CSS, then you might know the difference between ID and class selector, It's same with jQuery. ID selector uses ID e.g. #element1 to select element, while class selector uses CSS class to select elements. When you just need to select only one element, use ID selector, while if you want to select a group of element, having same CSS class than use class selector. There is good chance that, Interview will ask you to write code using  ID and class selector. Following jQuery code uses ID and class selectors :

$("#LoginTextBox")  -- Returns element wrapped as jQuery object with id="LoginTextBox"
$(".active") -- Returns all elements with CSS class active.

From syntax perspective, as you can see, another difference between ID and class selector is that former uses "#" and later uses "." character. More detailed analysis and discussion, see answer.



4. How do you hide an image on a button click using jQuery? (answer)

This jQuery interview question is based on event handling. jQuery provides good support for handling events like button click. You can use following code to hide an image, found using Id or class. What you need to know is hide() method and how to setup an even handler for button, to handle clicks, you can use following jQuery code to do that :

$("#ButtonToClick").click(function(){
    $("#ImageToHide").hide();
});

I like this jQuery question, because it's like a practical task and also code is not difficult to write.



5. What is $(document).ready() function? Why should you use it? (answer)

This is one of the most important and frequently asked jQuery Interview question. ready() function is used to execute code when document is ready for manipulation. jQuery allows you to execute code, when DOM is fully loaded i.e. HTML has been parsed and DOM tree has been constructed. Main benefit of $(document).ready() function is that, it works in all browser, jQuery handles cross browser difficulties for you. For curious reader see answer link for more detailed discussion.



6. Difference between JavaScript window.onload event and jQuery ready function? (answer)

This is the follow-up of previous jQuery interview question. Main difference between JavaScript onload event and jQuery ready function is that former not only waits for DOM to be created but also waits until all external resources are fully loaded including heavy images, audios and videos.  If loading images and media content takes lot of time that user can experience significant delay on execution of code defined in window.onload event. On the other hand jQuery ready() function only wait for DOM tree, and does not wait for images or external resource loading, means faster execution. Another advantage of using jQuery $(document).ready() is that you can use it multiple times in your page, and browser will execute them in the order they appear in HTML page, as opposed to onload technique, which can only be used for a single function. Given this benefits, it's always better to use jQuery ready() function than JavaScript window.onload event.  See answer article for more deep discussion.



7. How do you find all selected options of HTML select tag? (answer)

This is one of the tricky jQuery question on Interviews. It's still a basic, but don't expect every jQuery beginners to know about this. You can use following jQuery selector to retrieve all selected options of <select> tag with multiple=true :

$('[name=NameOfSelectedTag] :selected')

This code uses attribute selector in combination of :selected selector, which returns only selected options. You can tweak this and instead of name, you can even use id attribute to retrieve <select> tag.



8. What is each() function in jQuery? How do you use it? (answer)

each() function is like Iterator in Java, it allows you to iterate over a set of elements. You can pass a function to each() method, which will be executed for each element from the jQuery object, on which it has been called. This question sometime asked as follow-up of previous question e.g. how to show all selected options in alert box. We can use above selector code to find all selected option and than further can use each() method to print them in alert box, one by one, as shown below:

$('[name=NameOfSelectedTag] :selected').each(function(selected){
        alert($(selected).text());
});


text() method returns text for that option.



9. How do you add an HTML element in DOM tree? (answer)

You can use jQuery method appendTo() to add an HTML element in DOM tree. This is one of the many DOM manipulation method jQuery provides. You can add an existing element or a new HTML element, appendTo() add that method in the end of a particular DOM element.



10. Can you write jQuery code to select all links, which is inside paragraphs? (answer)

Another jQuery interview question based on selector. This also required to write jQuery one liner, like many other questions. you can use following jQuery snippet to select all links (<a> tag) nested inside paragraphs (<p> tag).



11. Difference between $(this) and this keyword in jQuery? (answer)

Could be a tricky questions for many jQuery beginners, but indeed it's simplest one. $(this) returns a jQuery object, on which you can call several jQuery methods e.g. text() to retrieve text, val() to retrieve value etc, while this represent current element, and it's one of the JavaScript keyword to denote current DOM element in a context. You can not call jQuery method on this, until it's wrapped using $() function i.e. $(this).



12. How do you retrieve attribute of an HTML tag using jQuery e.g. href of links? (answer)

attr() method is used to retrieve value of an attribute of any HTML element. You first need to select all links or specified links using jQuery selector and than you can apply attr() method to get value of there href attribute. Below code will find all links from a page and return href value :

$("a").each(function(){
   alert($(this).attr('href'));
});



13. How do you set attribute using jQuery? (answer)

One more follow-up question of previous jQuery question, attr() method is overload like many other methods in JQuery. If you call attr() method with value e.g. attr(name, value), where name is the name of attribute and value is the new value.



14. What is difference between detach() and remove() method in jQuery? (answer)

Though both detach() and remove() method is used to remove a DOM element,Main difference between them is that detach() keep track of the last element detached, so that it can be reattached, while remove() method does keep reference of last removed method. This is one of the many jQuery interview question from DOM manipulation. You can also take a look on appendTo() for adding element into DOM.



15. How do you add and remove CSS classes to an element using jQuery? (answer)

By using addClass() and removeClass() jQuery methods. This can be very handy, while dynamically changing class of elements e.g. marking them inactive or active and using class ".active" etc.



16. What is main advantage of loading jQuery library using CDN? (answer)

This is slightly advanced jQuery question, and don't expect that jQuery beginners can answer that. Well, apart from many advantages including reducing server bandwidth and faster download, one of the most important is that, if browser has already downloaded same jQuery version from same CDN, than it won't download it again. Since now days, almost many public websites use jQuery for user interaction and animation, there is very good chance that browser already have jQuery library downloaded. Curious reader, please see the answer for in depth analysis.

Good jQuery Interview Questions with Answers


That's all on this list of 16 jQuery interview questions and answers for beginners. As I said already, these questions are pretty basic, but most likely asked to web developers including Java. For an Interviewer, you can use this question to check if candidate has really used jQuery or not. Since an Interview for a client side position almost always contains loads of questions from HTML, CSS and JavaScript, you got to prepare that as well, along with jQuery questions. By the way, if you have faced any other question on jQuery interviews and wants to share with us, you can do so by commenting in this article. You can also asked any jQuery question, asked to you on interviews.

Saturday 21 February 2015

Scala vs Java - Differences and Similarities

Scala is new generation JVM language, which is generating popularity as alternative of arguable one of the most popular language Java. It's not yet as popular as Java, but slowly getting momentum. As more and more Java developers are learning Scala and inspired by Twitter, more and more companies are using Scala, it's future looks very bright. To start with, Scala has several good feature, which differentiate it from Java, but same time it has lot of similarities as well e.g. both Scala and Java are JVM based language, You can code Scala in Java way and Scala can use any Java library, which in my opinion a great decision made by designers of Scala. Since tremendous works has already been done in form of open source framework and library in Java, it's best to reuse them, rather than creating a separate set for Scala. Out of several differences, one of the main difference between Scala and Java is it's ability to take advantage of Functional programming paradigm and multi-core architecture of current  CPU. Since current CPU development trend is towards adding more cores, rather than increasing CPU cycles, it also favors functional programming paradigm. Though this differences may not be significant, once Java 8 will introduce lambdas, but it might be too early to comment. Apart from functional programming aspect, there are many other differences as well. One of the obvious one is improved readability and succinct code. Java is always on firing line for being too verbose, I thing Scala does take care of that and code which took 5 to 6 lines in Java, can be written in just 2 to 3 lines in Scala. Well Grounded Java Developer has some nice introduction on JVM languages like Scala, Groovy and Closure, which is worth reading.  In this article, we will see such kind of similarities and differences between Scala and Java.




Similarities between Scala and Java

Following are some of the major similarities between Scala and Java programming language :

1) Both are JVM based language, Scala produce same byte code as Java and runs on Java Virtual Machine. Similar to Java compiler javac, Scala has a compiler scalac, which compiles Scala code into byte code. At this level, all JVM language like Groovy, JRuby, Scala becomes equals to Java, because they use same memory space, type system and run inside same JVM.

2) You can call Scala from Java and Java from Scala, it offers seems less integration. Moreover, you can reuse existing application code and open source Java libraries in Scala.

3) Major Java programming IDE like Eclipse, Netbeans and InetelliJ supports Scala.

4) One more similarity between Scala and Java is that both are Object Oriented, Scala goes one steps further and also supports functional programming paradigm, which is one of it's core strength.

Differences between Scala and Java

1) First and Major difference you will notice between Scala and Java is succinct and concise code. Scala drastically reduce number of lines from a Java application by making clever use of type inference, treating everything as object, function passing and several other features.

2) Scala is designed to express common programming patterns in elegant, concise and type-safe way. Language itself encourage you to write code in immutable style, which makes applying concurrency and parallelism easily.

3) One difference, which some might not notice is learning curve. Scala has steep learning curve as compared to Java, my opinion may be slightly biased because I am from Java background, but with so much happening with little code, Scala can be really tricky to predict. Syntax of Scala looks confusing and repulsive as compared to Java, but I am sure that is just the starting hurdle. One way to overcome this hurdle is following a good Scala book like  Programming in Scala or Scala in Action, both are excellent books for a Java developer, who wants to learn Scala

4) One of Scala's cool feature is built-in lazy evaluation, which allows to defer time consuming computation, until absolutely needed and you can do this by using a keyword called "lazy" as shown in below code :
 
// loading of image is really slow, so only do it if need to show image
lazy val images = getImages()  //lazy keyword is used for lazy computation
if(viewProfile){
    showImages(images)
}
else(editProfile){
    showImages(images)
    showEditor()
}
else{
    // Do something without loading images.
}

If you love to learn by following examples, then I guess Scala CookBook is a another good buy, contains tons of examples on different features of Scala.

5) Some one can argue that Java is more readable than Scala, because of really nested code in Scala. Since you can define functions inside function, inside another functions, inside of an object inside of a class. Code can be very nested. Though some time it may improve clarity, but if written poorly it can be really tricky to understand.

6) One more difference between Scala and Java is that Scala supports Operator overloading. You can overload nay operator in Java and you can also create new operators for any type, but as you already know, Java doesn't support Operator Overloading.

7) Another major difference between Java and Scala is that functions are objects in Java. Scala treats any method or function as they are variables. When means, you can pass them around like Object. You might have seen code, where one Scala function is accepting another function. In fact this gives the language enormous power.

8) Let's compared some code written in Scala and Java to see How much different it look:


Java:
List<Integer> iList = Arrays.asList(2, 7, 9, 8, 10);
List<Integer> iDoubled = new ArrayList<Integer>();
for(Integer number: iList){
    if(number % 2 == 0){
        iDoubled.add(number  2);
    }
}
Scala:
val iList = List(2, 7, 9, 8, 10);
val iDoubled = iList.filter(_ % 2 == 0).map(_  2)

You can see that Scala version is lot succinct and concise than Java version. You will see more of such samples, once you start learning functional programming concepts and patterns. I am eagerly waiting for Scala Design Patterns: Patterns for Practical Reuse and Design by John Hunt, which is not yet released and only available for pre order. This book is going to release this month.


That's all on this article about similarities and differences between Scala and Java.  Though they are two separate programming language, they have lot in common, which is not a bad thing at all and in my opinion that's the only thing, which will place Scala as Java alternative, if at all it happens in future. As I had mentioned in my post 10 reason to learn Java programming, that Java tools, libraries, and community is it's biggest strength and if Scala can somehow reuse that, it will be well ahead, forget about competing though, it will take years to build such community and code. For a Java programmer, I would say nothing harm in learning Scala, most likely you will learn few good practices, which you can even apply in Java, as corporate sector is still on Java, and Scala in it's early days, you can be well ahead, if you learn Scala now. On closing note, at high  level Scala looks very promising, all design decision made are really good and they came after several years of experience with Java.


Recommended Books on Scala for Java Programmers

Books are best way to learn a new programming language, first of all they contains complete information but also in much more readable and authentic form. I strongly recommend to follow at-least one book, before jumping on blogs and online articles. One reading any Scala Programming book is must to build fundamental, which is indeed necessary, given rather steep learning curve of Scala. Following are my list of some books from which you can choose one.

Programming in Scala: A Comprehensive Step-by-Step Guide, 2nd Edition by Martin Odersky, Lex Spoon and Bill Venners
Scala for the Impatient by Cay S. Horstmann
Scala in Depth by Joshua D. Suereth and Martin Odersky

Blog Archive