Search This Blog

Tuesday, 31 March 2015

10 difference between Java and JavaScript for Programmers


Programmers, developers and internet users  have always been confused between Java and JavaScript.  Many people still thinks that JavaScript is part of Java platform, which is not true. In truth, JavaScript has nothing to do with Java, only common thing between them is word "Java", much like in Car and Carpet, or Grape and Grapefruit. JavaScript is a client side scripting languagefor HTML, developed by Netscape, Inc, while Java is a programming language, developed by Sun Microsystems. James Gosling is Inventor of Java, popularly known as father of Java. While in today's world calling JavaScript just a client side scripting language would not be good, as its now been used in servers also using node.js and people are doing object oriented development in JavaScript, but that was what it was originally developed. There are several difference between Java and JavaScript, from how they are written, compiled and executed. Even capability of Java and JavaScript vary significantly. Java is full feature Object oriented programming language, used in almost everywhere, starting from programming credit card to server side coding. Android uses Java as programming language for creating Android apps, Swing is a Java API used to create desktop applications and Java EE is a Java platform for developing web and enterprise applications. On the other hand JavaScript is primarily used to bring interactivity into web pages, though there are other alternatives like Flash, JavaScript is the most popular one and regaining lots of ground lost earlier with introduction of powerful and easy to use libraries like jQuery and jQuery UI. You can use JavaScript to validate user input, create animation and cool effects in HTML page and can do lot of interactive stuff e.g. reacting on button click, mouse movement, image click etc. In this article, I will share some key differences between Java and JavaScript, mostly from a programmers perspective.
Here is my list of key differences between JavaScript and Java as programming languages. I have worked both on them, mainly used Java for all Server Side development, Android and JavaScript for writing client side scripts to do validation, interactivity, animation and ajax calls.
Difference between Java and JavaScript
1) Execution Environment



First difference between Java and JavaScript is that Java is compiled + interpreted language, Java code is fist compiled into class files containing byte code and than executed by JVM, on the other hand JavaScript code is directly executed by browser. One more difference which comes form this fact is that, Java is run inside JVM and needs JDK or JRE for running, on there other hand JavaScript runs inside browser and almost every modern browser supports JavaScript.

2) Static vs Dynamic Typed language



Another key difference between JavaScript and Java is that, JavaScript is a dynamic typed language, while Java is a statically typed language. Which means, variables are declared with type at compile time, and can only accept values permitted for that type, other hand variables are declared using vary keyword in JavaScript, and can accept different kinds of value e.g. Stringnumeric andboolean etc. When one variable or value is compared to other using == operator, JavaScript performs type coercion. Though it also provides === operator to perform strict equality check, which checks for type as well. See here for more differences between == and == operator in JavaScript.

3) Support of Closures



JavaScript supports closures, in form of anonymous function. In simple words, you can pass a function as an argument to another function. Java doesn't treat method as first class citizen and only way to simulate closure is by using anonymous class. By the  way Java 8 has brought real closure support in Java in form of lambda expression and this has made things much easier. It's very easy to write expressive code without much clutter in Java 8.

4) OOP



Java is an Object Oriented Programming language, and though JavaScript also supports class and object, it's more like an object oriented  scripting language. It's much easier to structure code of large enterprise application in Java then JavaScript. Java provides packages to group related class together, provides much better deployment control using JAR, WAR and EAR as well.

5) Right Once Run Anywhere



Java uses byte code to achieve platform independence, JavaScript directly runs on browser, but code written in JavaScript is subject to browser compatibility issue i.e. certain code which work in Mozilla Firefox, may not work in Internet Explorer 7 or 8. This is because of browse based implementation of JavaScript. This was really bad until jQuery comes. Its a JavaScript library which helps to free web developers from this browser compatibility issues. This is why I prefer to write code using jQuery rather than using plain old JavaScript code, even if its as simple as calling getElementById() or getElementByName() methods to retrieve DOM elements.

7) Block vs Function based Scoping



Java mainly uses block based scoping i.e. a variable goes out of scope as soon as control comes out of the block, unless until its not a instance or class variable. On the other hand JavaScript mainly uses function based scoping, a variable is accessible in the function they are declared. If you have a global variable and local variable with same name, local will take precedence in JavaScript.

8) Constructors



Java has concept of constructors, which has some special properties e.g. constructor chaining and ensuring that super class constructor runs before sub class, on the other hand JavaScript constructors are just another function. There is no special rules for constructors in JavaScript e.g. they cannot have return type or their name must be same as class.

9) NullPointerException



JavaScript is much more forgiving than Java, you don't have NullPointerException in JavaScript, your variable can accept different kinds of data because of JavaScript is dynamically typed language.

10) Applicability



Last but not the least, JavaScript has it's own space, sitting cozy along with HTML and CSS in Web development, while Java is everywhere. Though both has good number of open source libraries to kick start development, but jQuery has certainly brings JavaScript on fore front.
That's all on difference between Java and JavaScript language. As I said, they are totally different language, one is a general purpose programming language, while other is scripting language for HTML. Though you can do lot of fancy stuffs using JavaScript, you still don't have features like multithreading, as compared to Java. By the way JavaScript was originally named as Livescrpit, may be due to the fact that it makes your HTML pages live, and programming world would certainly be free of this confusion, had Netscape hadn't renamed LiveScript as JavaScript.



Thursday, 26 March 2015

How to reverse array in place in Java?

Reversing an array sounds pretty easy, isn't it? It does sounds like that, because all you need to do is create an array of same size, iterate through original array from end to start and populate your new array. Boom!!, you have got an array which has elements in reverse order of original array, but problem is you have used and additional array here, which makes space complexity of your solutionO(n). You cannot use this solution if array is big e.g. an array of 10 million orders and you don't have enough heap space available. Can we make it better? Can we reverse array in Java without using an additional buffer? Even If you encounter this question in your programming job interview, you will be surely asked to reverse array in placewithout using an additional buffer as earlier solutiontakes lot of space. So now your task is to write a Java program to reverse an array in place. For the sake of this problem, you can assume that its an integer array (during interview, you should ask these question to your interviewer, because asking right question to fill the gap in requirement is a trait of good programmer and highly appreciated on both telephonic and face-to-face interviews). Key point to understand here is that you need to reverse the same array, you cannot use another array but one or two variable is fine. You are also not allowed to use any open source library or Java API which can reverse the array directly e.g. any method from java.util.Arrays class except Arrays.toString()to print arrays in Java. So now the requirement is clear, what approach comes in your mind? how do you solve this problem?


Java Program to Reverse Array In Place

The first thing which comes in my mind is to loop through array and swap the elements of array e.g. swap first element with last element, swap second element with second last element until you reach the middle of the array. This way, all elements of array will be reversed without using any additional buffer. Key thing to keep in mind in this algorithm is that you only need to iterate till middle element, if you go beyond that then you end up swapping elements twice and result in same array. Some of you will be puzzled, what is length of array is even? In that case there will be two middle element and we need to swap them, that's why your loop condition should be index <= middle and not index < middle. Here middle index is nothing but length/2. Remember, we are using division operator, which means if length is 8 then it will return 4 and when length is 7 it will return 3. So in case of even length, the middle element will be swapped twice, but in case of odd length there is just one middle element and it will not be swapped.

It's been said time and again that a picture is worth a thousand word and true to the point, this image explains the algorithm we used to reverse array in place quite well. You can see that how elements of arrays are swapped position with each other and middle element remain unchanged, with just two swapping we have reversed an array of five elements.

Algorithm to reverse array in place in Java

Here is our sample Java program to reverse array in placesolution is simple and easy to follow, but don't forget to look my JUnit tests to understand it bit more.

import java.util.Arrays;

/**
 * Java Program to demonstrate how to reverse an array in place.
 */
public class ArrayReversalDemo {

    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5, 6, 7};
        reverse(numbers);
    }

    /**
     * reverse the given array in place 
     * @param input
     */
    public static void reverse(int[] input) {
        System.out.println("original array : " + Arrays.toString(input));
        
        // handling null, empty and one element array
        if(input == null || input.length <= 1){
            return;
        }       
        
        for (int i = 0; i < input.length / 2; i++) {
            int temp = input[i]; // swap numbers
            input[i] = input[input.length - 1 - i];
            input[input.length - 1 - i] = temp;
        }

        System.out.println("reversed array : " + Arrays.toString(input));
    }
    
    
}

Output
original array : [1, 2, 3, 4, 5, 6, 7]
reversed array : [7, 6, 5, 4, 3, 2, 1]
original array : []
original array : null
original array : [1, 2, 3, 4, 5, 6]
reversed array : [6, 5, 4, 3, 2, 1]
original array : [1]

You can see in output here that input array is reversed properly and in case of null, empty and array with just one element, same array is returned.

JUnit tests

Here is my suite of JUnit tests for our reverse(int[] input)  method. I have made sure to test our solution can handle null, empty array, an array with just one element, and array with even or odd number of elements. You can even test drive this problem. Writing Unit test is a good practice and during Interview you must write JUnit test even if Interview has not asked for it. This shows that you are a professional software developer and you care for your trade.
import static org.junit.Assert.assertArrayEquals;

import org.junit.Test;

public class ArrayReversalDemoTest {
    
    @Test
    public void testReverseWithEvenLengthOfArray(){
        int[] numbers = {1, 2, 3, 4, 5, 6};
        HelloWorld.reverse(numbers);
        assertArrayEquals(new int[]{6, 5, 4, 3, 2, 1}, numbers);
    }
    
    @Test
    public void testReverseWithOddLengthOfArray(){
        int[] numbers = {1, 2, 3, 4, 5, 6, 7};
        HelloWorld.reverse(numbers);
        assertArrayEquals(new int[]{7, 6, 5, 4, 3, 2, 1}, numbers);
    }
    
    @Test
    public void testReverseWithEmptyArray(){
        int[] numbers = {};
        HelloWorld.reverse(numbers);
        assertArrayEquals(new int[]{}, numbers);
    }
    
    @Test
    public void testReverseWithNullArray(){
        int[] numbers = null;
        HelloWorld.reverse(numbers);
        assertArrayEquals(null, numbers);
    }
    
    @Test
    public void testReverseWithJustOneElementArray(){
        int[] numbers = {1};
        HelloWorld.reverse(numbers);
        assertArrayEquals(new int[]{1}, numbers);
    }
   
}

and here is the output of running our unit tests, they all pass.

How to reverse array in place in Java



That's all about how to reverse array in place in Java. Time complexity of this method is O(n/2) or O(n) because it only iterate through half of the array, but its in O(n) because response time increases in same order as input increases. As a task, can you find a faster solution of this problem?


Tuesday, 17 March 2015

Top 10 Popular Programming languages and their Inventors

Here is my list of top 10 programming language and their creators. Languages are listed on no particular order, but since I am a Java developer and benefited a lot from Java, I have no hesitation to put it on top of the list. I know many C programmer will not agree as C is the longest surviving, yet going strong programming language, but this is not about ranking but about knowing and remembering their creators. The master programmers who has made difference in the world of programming language and software development.

1) Java - James Gosling

Java is one of the most popular and successful programming language. Dr. James Arthur Gosling is invented Java and best known as the father of the Java programming language. Java was developed and supported earlier by Sun Microsystem and now by Oracle, after their acquisition of Sun Microsystem on January 2010. Java is created with mission WORA, "Write Once Run Anywhere" and platform independence of Java is one of the pillar of it's success in the enterprise world. Till date, it is one of the most popular application programming language.


2) C - Dennis Ritchie

Dennis MacAlistair Ritchie, An American computer scientist, created the C programming language between 1967 and 1973 at AT&T Bell labs. C is still very popular and used extensively in System programming. It's older than Java but still maintains it's stronghold. By the way Dennis Ritchie has also created world famous UNIX operating system, with his long-time colleague Ken Thompson. If you compare his popularity with Bill Gates or Steve Jobs, he is no where but if you compare Dennis' contribution to the software world, he has no matching. Every Programmer must know about Dennis Ritchie and his contribution to the programming world.

 

3) C++ - Bjarne Stroustrup

Bjarne Stroustrup; born 30 December 1950 in Aarhus, Denmark is a Danish computer scientist, most notable for the creation and the development of the widely-used C++ programming language. C++, as name suggested is the next generation language at time C was popular. It comes with object oriented programming feature which was considered phenomenal compared to structural way of C programming. C++ is still one of the very popular language and used extensively in high frequency trading world because of its close proximity with native System and popular object oriented feature.



4) Python - Guido van Rossum

Python is a general-purpose, high-level programming language, whose design philosophy emphasizes code readability. Its syntax is said to be clear and expressive.Python is designed by Guido van Rossum of CWI. In United states, Python has actually replaced Java at academic level, now days students are started learning programming using Python instead of C or Java, as was the case of previous generation. If you are still not sure whether to use Python or Java to start with programming, this infographic may help you. Python is used extensively in web application development, there are lots of python based web framework out there, software development and information security. Python is also used extensively by tech giants like Google, Yahoo and Spotify.



5) PHP - Rasmus Lerdorf

No matter how much you hate PHP, you just can't ignore the fact that half of the internet is running on this wonderful internet language. PHP was originally created by Rasmus Lerdorf in 1995. The main implementation of PHP is now produced by The PHP Group and serves as the formal reference to the PHP language. That time, PHP was a competitor to Microsoft's Active Server Pages (ASP) server-side script engine and similar languages e.g. Java Server Pages (JSP), but gradually received better acceptance and is now installed on more than 20 million Web sites and 1 million Web servers. It is also open source and used by internet giants like Facebook, Wikipedia, Wordpress and Joomla. PHP is used extensively to to build dynamic web pages and server side development. Sorry, I forgot to tell you the full form of PHP, any guess? Its Personal Home Page :)



6) Perl - Larry Wall

Perl is a high-level, general-purpose, interpreted, dynamic programming language. designed and developed by Larry Wall in the mid-1980's. Perl rose to fame because of its excellent text processing capability. It is still main language to develop reports, scripts on UNIX systems. Perl is known for parsing and processing large text files and its used in CGI, database applications, network programming and graphics programming. Perl is also used extensively by internet companies like IMDB, Amazon, and Priceline. For Java developers, adding Perl or Python in their portfolio is good addition because you often need a scripting language to do adhoc tasks for maintenance and support purpose.



7) JavaScript - Brendan Eich

If you ask me, which language is the winner in last 5 to 10 years, I would say JavaScript. It has clearly dominated the client side scripting space in recent past with libraries like jQuery and now moving to Server side development with libraries like node.js. JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions, designed by Brendan Eich and developed by Netscape Communications Corporation. JavaScript is used extensively for client side scripting, validation, animation, event capturing, form submission and other common task. It runs inside browser and used by almost all websites e.g. Gmail, Mozila Firefox etc.



8) Ruby - Yukihiro Matsumoto

Ruby was first designed and developed in the mid-1990s by Yukihiro "Matz" Matsumoto in Japan. Its fun working with Ruby and if you tried Ruby with Rails you know what I mean. Ruby is influenced by Perl, Ada, Lisp and Smalltalk and designed for productive and enjoyable programming. Ruby is mostly used for web application development and used by major sites like Twitter, Hulu and Groupon.



9) Lisp - John McCarthy

John McCarthy , second oldest high level programming language. Lisp stands for List processor. I have never tried Lisp but its said to be father of functional programming language e.g. Haskell, Erlang or Scala. It is used for AL development and air defense system.



10) Pascal - Niklaus Wirth

Pascal is an influential imperative and procedural programming language, designed in 1968–1969 and published in 1970 by Niklaus Wirth as a small and efficient language intended to encourage good programming practices using structured programming and data structuring.
and here is the infographic, which gives you a nice overview of 10 programming language and their creators. It contains some of the language mentioned here, plus some additional language like FORTRAN and Ada.
Top 10 Programming Language and creators
That's all about top 10 programming languages and their Inventors. They have made huge difference in programming world and without their contribution, we would not be here. Some of them are here with us and some of them has left us for better place, let's remember them for their contribution to our programming world.



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 &lt;= startIndex &amp;&amp; queryEnd &gt;= endIndex )  // base case
   return treeNode[current];

if (endIndex &lt; queryStart || startIndex &gt; 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 &lt; 0 || queryEnd &gt; 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 &lt; startIndex || updatePos &gt; 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 ...!!!

Blog Archive