Posts

Showing posts with the label data structure and algorithm

Bucket Sort in Java with Example

In recent years, one of the question I have increasingly seen in programming job interviews is about constant time sorting algorithms e.g. do you know any O(n) sorting algorithm? When I first encountered this question, I had no idea whether we can sort in constant time because even some of the fastest sorting algorithms e.g. QuickSort or MergeSort takes O(N log N) time for sorting. After some research, I come to know that there are some constant time algorithms e.g. bucket sort, counting sort and radix sort, which can sort an array in O(n) time. The idea of bucket sort is quite simple, you distributes the elements of an array into a number of buckets and then sort those individual bucket by a differnet sorting algorithm or by recursively applying the bucket sorting algorithm. Read more �

How to Count Number of Leaf Nodes in Binary Tree - Java Iterative and Recursive Algorithm

You can use the same algorithm to count a number of leaf nodes in the binary tree which we have used in the last article, while printing all leaf nodes of a binary tree in Java , using both recursion and iteration. The logic is same for leaf node, any node whose left and right children is null is known as leaf node in binary tree. They are the nodes which resides in the last level of binary tree and they don't have any children. In order to count total number of leaf nodes in binary tree, you need to traverse the tree and increase the count variable whenever you see a leaf node. Since binary tree is an essential data structure and algorithm topics for programming interviews , its better to prepare these kind of questions. I'll show how to solve this using both recursion and iteration in Java in this article. Read more �

How to find square root of a number in Java - Algorithm Interview question

Write a program to calculate the square root of a number in Java or C++ is one of the popular coding interview questions from Programming job interviews both on tech companies like Facebook, Amazon, and investment banks like Citibank and Bank Of America etc. The problem may look easy because you might know how to find the square root of a number but it's not. In fact, it's one of the tricky questions you would encounter in programming job interviews . The first hurdle is do you really remember how to calculate square root by hand? Many programmers don't. I know they have learned it past but when you ask them to calculate square root by hand, many won't remember the algorithm they have learned in school or college. Read more �

Post Order binary tree traversal in Java - Recursion and Iteration

This is the third article on tree traversal. In the last couple of articles, I have shown you how to implement preorder and inorder traversal in Java, both recursively and iteratively and today, you will learn about the post order traversal . Out of these three main tree traversal algorithms, the post-order traversal is most difficult to implement, especially the iterative version. In post order traversal, you first visit left subtree, then right subtree and at last you print the value of root or not. So, the value of root is always printed at last in the post-order traversal . As I told you before, all three preOrder, inOrder, and postOrder are depth-first algorithms so they go down in the binary tree first before visiting nodes of the same level. The implementation of the recursive algorithm is very simple, you just need to adjust the order of recursive call according to the algorithm and you are done, but iterative algorithm requires some effort to get it right, which you will s...

How to check if two Rectangle Overlap in Java - Algorithm

Can you write a Java program to check if two rectangles are overlapping with each other or not? is one of the frequently asked coding questions on tech giants like Facebook, Amazon, Microsoft and others. This is also a kind of problem where it's easy to find opposite or negative conditions e.g. when rectangles are not overlapping and then inverting the result to prove that rectangles are colliding with each other. I first heard about this problem from one of my friend who was on Android game development space. He was asked to write an algorithm to find if given rectangles are intersecting or not. He was given the choice to implement the algorithm in any programming language e.g. Java, C, C++ or even pseudo code was fine, so don't worry about language here, it's more about algorithm and logic. He is a genius so he came successful from that interview, impressing the interviewer, talking about efficiency and accuracy of the algorithm as well. Read more �

Iterative QuickSort Example in Java - without Recursion

The quicksort algorithm is one of the important sorting algorithms. Similar to merge sort, quicksort also uses divide-and-conquer hence it's easy to implement quicksort algorithm using recursion in Java, but it's slightly more difficult to write an iterative version of quicksort. That's why Interviewers are now asking to implement QuickSort without using recursion. The interview will start with something like writing a program to sort an array using quicksort algorithm in Java and most likely you will come up with a recursive implementation of quicksort as shown here . As a follow-up, Interviewer will now ask you to code the same algorithm using Iteration. Read more �

How to Print all Leaf Nodes of Binary tree in Java - Recursion and Stack

Binary tree based questions are very common in Java or any other Programming job interviews. One of the frequently asked binary tree questions is "write a program to print all leaf nodes of a binary tree" . In order to solve this problem, you must know what is a leaf node? A leaf node in a binary tree is a node whose left and right child is null . They are actually the last nodes of any binary tree. In a typical programming interview, you would be given a binary tree and asked to write a program to print all leaf nodes. Usually, all binary tree related questions can be solved easily using recursion because a tree is a recursive data structure, but you should also know how to solve them without recursion. Read more �

InOrder traversal of Binary tree in Java using Recursion and Iteration

This is the second article about tree traversal algorithms using Java. In the first part , we have seen the pre-order algorithm for visiting all nodes of the binary tree and today we'll learn about the InOrder traversal . As I told you before, unlike array and linked list , binary tree has several ways of traversal. The traversal algorithms are broadly divided into depth first and breadth first traversal algorithms depending upon how algorithm actually works. As the name suggest, depth first explores binary tree towards depth before visiting sibling, while breath first visits all nodes in the same level before going to next level, hence it is also known as level order traversal. Both PreOrder and InOrder tree traversal algorithms are depth first and the only difference between pre-order and in-order algorithm is the order on which root, left node, and right node of the binary tree is visited. Read more �

How to find the 3rd element from end in linked list in Java

The problem to find the 3rd element from the end in a singly linked list or nth node from the tail is one of the tricky but frequently asked linked list problems in programming job interviews. The challenge here is to solve the problem in just one pass, i.e. you can not traverse the linked list again and you cannot traverse backward because it's a singly linked list. If you have practiced some linked list problems e.g. finding length , inserting elements, or deleting elements then you should be familiar with traversal. Here, we'll use the same algorithm which we have used to find the middle element of linked list in one pass . The algorithm is also known as tortoise and hare algorithm because of the speed of two pointers used by the algorithm to traverse the singly linked list. Read more �

Binary Tree PreOrder Traversal in Java - Recursion and Iteration Example

Unlike linked list and array which can only be traversed linearly, there are several ways to traverse a binary tree. The tree traversal algorithms are mainly divided into two parts, depth first and breadth first . As their name suggests, in depth first, the tree is traversed downwards (towards the depth) before the next sibling is visited, the PreOrder , InOrder and PostOrder traversal of a binary tree are actually depth-first traversals. On the breadth first, the entire breadth of the tree is traversed before moving to next level, hence it is also known as level order traversal. There are other algorithms to traverse a binary tree as well e.g. Monte Carlo tree search, which concentrates on analyzing the most promising moves, but the pre-order, post-order, and in-order traversal are the most popular ways to traverse a binary tree in Java. They are also the most popular data structure and algorithm questions at beginner and intermediate level. Read more �

How do you find length of a Singly Linked list using Loop and Recursion

Hi Guys, Here is one of the classical programming questions asked to me first time on an interview with multinational Investment bank. After that, this question has been asked to me on several occasions in other programming job interviews as well. What makes this question interesting is that Java developers are not that great with the data structure as compared to C++ developer which is obvious because of the fundamental difference between these two languages. The C++ is more of system programming language while Java is more on application programming , also a rich set of Java API allows the programmer to skip this kind of basic programming techniques. Read more �

How to Reverse Array in Java - Int and String Array Example

This Java tips is about, how to reverse array in Java, mostly primitive types e.g. int , long , double and String arrays. Despite of Java�s rich Collection API, use of array is quite common, but standard JDK doesn�t has great utility classes for Java. It�s difficult to convert between Java Collection e.g. List , Set to primitive arrays. Java�s array utility class java.util.Arrays , though offers some of critical functionalities like comparing arrays in Java and support to print arrays , It lacks lot of common features, such as combining two arrays and reverse primitive or object array. Thankfully, Apache commons lang, an open source library from Apache software foundation offers one interesting class ArrayUtils, which can be used in conjunction with java.util.Arrays class to play with both primitive and object array in Java. This API offers convenient overloaded method to reverse different kinds of array in Java e.g. int, double, float, log or Object arrays. On a similar note,...

How to generate MD5 Hash in Java - String Byte Array digest Example

There are multiple ways to generate the MD5 hash in Java program. Not only Java API provides a convenient method for generating MD5 hash, you can also use popular open source frameworks like Spring and Apache commons Codec to generate MD5 digest in Java. MD5 is popular Message Digest Algorithm, which is most commonly used to check data integrity e.g. comparing MD5 checksum to see, if any file is altered or not. Though MD5 has not considered a good cryptographic algorithm for security purpose due to several vulnerabilities found on it, it's still good enough or checking the integrity of the file. MD5 hashing algorithm generates a 128 bit or 16-byte long hash value. MD5 hash values , also known as MD5 digest is mostly represented as 32 character Hex String. You can generate an MD5 hash from a byte array , or String directly using Java, Spring and Apache commons codec. Spring and Apache commons codec has identical API e.g. class name DigestUtil s is same and allows you to directl...

Top 15 Data Structures and Algorithm Interview Questions for Java programmer - Answers

Data structures and algorithm questions are an important part of any programming job interview, be it a Java interview, C++ interview or any other programming language. Since data structures are core programming concept, it's mandatory for all programmers, to know basic data structures like stack, linked list, queue, array, tree, and graph. Though tree and graph are on the tough side, I still see programmers get familiar will all these. Any lis t of programming job interview questions is incomplete without questions from data structures and algorithms. Similarly, while going on questions from data structure you may get some programming exercise as well e . g. swapping numbers without temp variable. The li nked list and array are favorite topics in any data structure interview, questions like reversing linked list, traversing linked list or deleting nodes from linked list, which involves algorithm and data structures are quite common. Read more �

2 ways to combine Arrays in Java � Integer, String Array Copy Example

There are multiple ways to combine or join two arrays in Java, both for primitive like int array and Object e.g. String array. You can even write your own combine() method which can use System.arrayCopy() to copy both those array into the third array. But being a Java developer, I first looked in JDK to find any method which concatenates two arrays in Java. I looked at java.util.Arrays class, which I have used earlier to compare two arrays and print arrays in Java , but didn't find a direct way to combine two arrays. Then I looked into Apache Commons, ArrayUtils class, and bingo, it has several overloaded method to combine int , long , float , double or any Object array. Later I also found that Guava ,earlier known as Google collections also has a class ObjectArrays in com.google.common.collect the package, which can concatenate two arrays in Java. It's always good to add Apache commons and Guava , as supporting library in Java project, they have lots of supporting clas...

How to compare Arrays in Java � Equals vs deepEquals Example

java.util.Arrays class provides equals() and deepEquals() method to compare two Arrays in Java. Both of these are overloaded method to compare primitive arrays e.g. int, long, float, double and Object arrays e.g. Arrays.equals(Object[] , Object[]). Arrays.equals() returns true if both Arrays which it is comparing are null If both arrays pointing to same Array Object or they must be of the same length and contains the same element in each index. In all other cases, it returns false. Arrays.equals() calls equals() method of each Object while comparing Object arrays. One of the tricky question in Java related to Array comparison is Difference between Arrays.equals() and Arrays.deepEquals() method. Since both equals and deepEquals is used for array comparison, what is the difference between them becomes important. The short answer of this questions is that, Array's equals() method does not perform deep comparison and fails logical comparison in case of nested Array, on o...

Recursion in Java with example � Programming Techniques Tutorial

Recursion is one of the tough programming technique to master. Many programmers working on both Java and other programming languages like C or C++ struggles to think recursively and figure out the recursive pattern in the problem statement, which makes it is one of the favorite topics of any programming interview . If you are new in Java or just started learning Java programming language and you are looking for some exercise to learn the concept of recursion than this tutorial is for you. In this programming tutorial, we will see a couple of example of recursion in Java programs and some programming exercise which will help you to write recursive code in Java e.g. calculating Factorial , reversing String and printing Fibonacci series using recursion technique. For those who are not familiar with recursion programming technique here is the short introduction: "Recursion is a programming technique on which a method call itself to calculate result". It's not as simple as i...

3 Example to print array values in Java - toString and deepToString from Arrays

Printing array values in Java or values of array element in Java would have been much easier if arrays are allowed to directly prints its values whenever used inside System.out.println() or format and printf method , Similar to various classes in Java do this by overriding toString() method . Despite being an object, array in Java doesn't print any meaningful representation of its content when passed to System.out.println() or any other print methods. If you are using array in method argument or any other prominent place in code and actually interested in values of array then you don't have much choice than for loop until Java 1.4. Things has been changed since Java 5 because it introduced two extremely convenient methods for printing values of both primitive and object arrays in Java . Arrays.toString(array) and Arrays.deepToString(twoDimensionArray) can print values of any array. Main difference between Arrays.toString() and Arrays.deepToString is that deepToString i...

4 ways to search Java Array to find an element or object - Tutorial Example

Searching in Java Array sounds familiar? should be, because its one of frequently used operations in Java programming. Array is an index based data structure which is used to store elements but unlike Collection classes like ArrayList or HashSet which has contains() method, array in Java doesn't have any method to check whether an element is inside array or not. Java programming language provides several ways to search any element in Java array . In this Java tutorial we will see 4 examples of searching Array in Java for an element or object. Every example is different than other and some of them are faster and others are slow but take less memory. These technique also valid for different types of array e.g. primitive and object array. I always suggest to prefer List over Array until you need every bit of performance from your Java application, it not only convenient to work but also more extensible. Read more �