You are on page 1of 7

5/27/2015

BigOnotationquestionsandanswers|JavaSuccess.com

Java-Success.com

Register

Login

Logout

Contact

uTube

600+ Java Interview Questions Answered with lots of dagrams & code
Go

searchhere
Home

QuickPrep

Can u Debug?

600+ Q&A

Judging Experience

Java Career
Spring Tutorials

Tutorials

Membership

Java 8 Tutorials

Web

Other
CVs

Top X

Tools

Free content

Home Written Tests Java Data Structures & Algorithms Big O notation Big
O notation questions and answers

Big O notation
questions and answers
Posted on May 6, 2015 by akumaras

FAQs "". Free stu


"". User Reviews

600+ Java/JEE
Q&A
open all | close all

Q1. What do you know about the big-O notation and can
you give some examples with respect to dierent data
structures?
A1. The Big-O notation simply describes how well an
algorithm scales or performs in the worst case scenario as
the number of elements in a data structure increases. The
Big-O notation can also be used to describe other behavior
such as memory consumption. At times you may need to
choose a slower algorithm because it also consumes less
memory. Big-o notation can give a good indication about
performance for large amounts of data, but the only real
way to know for sure is to have a performance benchmark
with large data sets to take into account things that are not
considered in Big-O notation like paging as virtual memory
usage grows, etc. Although benchmarks are better, they
arent feasible during the design process, so Big-O
complexity analysis is the choice.
The algorithms used by various data structures for dierent
http://www.javasuccess.com/bigoquestionsandanswers/

Ice Breaker Interview Q&A


Memory Jogger Interview Q&A
Core Java Interview Q&A

JEE Interview Q&A


Java Companion Technologies Inter
Finance Domain Interview Q&A
Java Architecture Interview Q&A
JavaInterviewVideo
Top 100+ Quick Prep Java/JEE Interv
Sought-after Frameworks Interview
Spring
Hibernate
AngularJS
Git & SVN
JMeter
JMeter for testing RESTFul w
JMeter performance testing
JSF
Maven
1/7

5/27/2015

BigOnotationquestionsandanswers|JavaSuccess.com

operations like search, insert and delete fall into the

Testing Java Apps Q&A

following performance groups like constant-time O(1),


linear O(n), logarithmic O (log n), exponential O (cn),

Automation Testing Q&A


Performance Testing Q&A

polynomial O(nc), quadratic O (n2) and factorial O (n!)


where n is the number of elements in the data structure. It

Unit Testing Q&A


BDD Testing

is generally a tradeo between performance and memory

Java BDD (Behavior Driven D

usage. Here are some examples.

jBehave and BDD example


jBehave and jUnit for BDD

Example 1: Finding an element in a HashMap is usually a

jBehave with tabular story d

constant-time, which is O(1) . This is a constant time


because a hashing function is used to nd an element, and

Data Access Unit Testing


Java unit testing interview Qu

computing a hash value does not depend on the number of


elements in the HashMap.
Example 2: Linear search of an array, list, and LinkedList is
linear, which is O(n). This is linear because you will have to
search the entire list. This means that if a list is twice as big,
searching it will take twice as long.
Example 3: An algorithm that needs to compare every
element in an array to sort the array has polynomial
complexity, which is O (n2). A nested for loop is O (n2). An
example is shown under sorting algorithms.
Example 4: Binary search of a sorted array or ArrayList is
logarithmic, which is O(log n). Searching an element in a
LinkedList normally requires O(n). This is one of the
disadvantages of LinkedList over the other data structures
like an ArrayList or array oering a O (log n) performance,
which oers better performance than O(n) as the number
of elements increases. A logarithmic running times mean, if
10 items take at most x amount of time, 100 items will take
say at most 2x amount of time, and 10,000 items will take at
most 4x. If you plot this on a graph, the time decreases as n
(i.e. number of items) increases.

80+ Java coding


solutions
open all | close all
Can you write code?
Designing your classes & interfaces
Java Data Structures & Algorithms
Array Structure
Big O notation

Big O notation questions and


Understanding Big O notations
Graph Structure
LinkedList Structure
Map Structure
Pointer Algorithms
Queue Structure
Searching Algorithms
Sorting Algorithms
Stack Structure
Tree structure
Which Data Structure & WHy
Passing the unit tests
What is wrong with this code?
Written Test Core Java
Written Test JEE

http://www.javasuccess.com/bigoquestionsandanswers/

2/7

5/27/2015

BigOnotationquestionsandanswers|JavaSuccess.com

13+ Java Key


Areas

open all | close all


Best Practice
9 Java Data structures best practi

Top 5 Core Java Exceptions and b


10 Core Java Best Practices with
Java unit testing interview Ques

What happens to time as the number of items in the data structure


increases?

Q2. What can you tell about the performance of a HashMap


compared to a TreeMap? Which one would you prefer?
A2. A balanced tree does have O (log n) performance. The
TreeMap class in Java maintains key/value objects in a
sorted order by using a red-black tree. A red-black tree is a
balanced binary tree. Keeping the binary tree balanced
ensures the fast insertion, removal, and lookup time of O
(log n). This is not as fast as a HashMap, which is O(1) , but
the TreeMap has the advantage of that the keys are in
sorted order which opens up a lot of other capabilities.

How will you go about improving


Coding
Concurrency
Design Concepts
Design Patterns
Exception Handling
Judging Experience Interview Q&A
Memory Management
Performance
QoS
Scalability
SDLC
Security
Transaction Management

Which one to choose?


The decision as to using an unordered collection like a
HashSet or HasMap versus using a sorted data structure
like a TreeSet or TreeMap depends mainly on the usage
pattern, and to some extent on the data size and the
environment you run it on. The practical reason for keeping
the elements in sorted order is for frequent and faster
retrieval of sorted data if the inserts and updates are
frequent. If the need for a sorted result is infrequent like
prior to producing a report or running a batch process, then
maintaining an unordered collection and sorting them only
when it is really required with Collections.sort() could
sometimes be more e cient than maintaining the ordered
elements. This is only an opinion, and no one can oer you
a correct answer. Even the complexity theories like Big-O
notation like O(n) assume possibly large values of n. In
http://www.javasuccess.com/bigoquestionsandanswers/

Java Career
open all | close all
Beginner or Intermediate?
Did you get the Job oer?
Earning More
Feeling stagnated?
Freelancing & job security

Job hunting know how?


Personal branding, blogging, publish
Philosophies
Resume Writing
Sample Resumes
Soft Skills matter a lot
True value of Certication

3/7

5/27/2015

BigOnotationquestionsandanswers|JavaSuccess.com

practice, a O(n) algorithm can be much faster than a O(log


n) algorithm, provided the data set that is handled is
su ciently small. One algorithm might perform better on
an AMD processor than on an Intel. If your system is set up
to swap, disk performance need to be considered. The only
way to conrm the e cient usage is to test and measure
both performance and memory usage with the right data
size. Measure both the approaches on your chosen
hardware to determine, which is more appropriate.
Q3. What is the tradeo between using an unordered array
versus an ordered array?
A3. The major advantage of an ordered array is that the
search times are much faster with O (log n) than an
unordered array, which is O (n) for larger values of n. The
disadvantage of an ordered array is that the insertion takes
longer (i.e. O (n) ) because all the data with higher values
need to be moved to make room. The insertion for an
unordered array takes constant time of O(1). This means, it
does not depend on the number of elements. The following
code snippet demonstrates adding an element to both
ordered and unordered array.
Inserting an element into an unsorted array

packagebigo;
importjava.util.Arrays;
publicclassInsertingElementsToArray{
publicstaticvoidinsertUnsortedArray(String
String[]unsortedArray={"A","D","C"

Java Tutorials
open all | close all
Setting up Tutorial
Tutorial - Diagnosis
JEE Web & Web Services Tutorial
JSF Tutorial
SQL Tutorial
JDBC Tutorial
Hibernate Tutorial
Spring Tutorial
Spring batch tutorial
Drools Tutorial
JMeter Tutorial
Core Java Tutorial
Debugging Tutorial
DOS Tutorial
ESB Tutorials
FIX and Java Tutorial
JasperReport Tutorial
Java 8 Tutorial
JSON and Java Tutorial
JAXB Tutorial
JMX Tutorial
JPA-Hibernate-Spring Tutorial
JPA Tutorial
Logging and auditing Tutorial
Maven Tutorials
Metrics Tutorial
Productivity Tools Tutorial
Spring ORM Tutorial
Spring other tutorial
Spring OXM Tutorial
Unix Tutorial
XML and Java Tutorial
CSV and Java Tutorials

String[]newUnsortedArray=newString[
System.arraycopy(unsortedArray,0,newUnsortedArray
newUnsortedArray[newUnsortedArray.length
System.out.println(Arrays.toString(newUnsortedArray
}

http://www.javasuccess.com/bigoquestionsandanswers/

4/7

5/27/2015

BigOnotationquestionsandanswers|JavaSuccess.com

publicstaticvoidmain(String[]args){
insertUnsortedArray("B");
}
}

Inserting an element into a sorted array

packagebigo;
importjava.util.Arrays;
publicclassInsertingElementsToArray{
publicstaticvoidinsertSortedArray(StringtoInsert
String[]sortedArray={"A","C","D"
/*
*Binarysearchreturnstheindexofthesearchitem
*iffound,otherwisereturnstheminusinsertionpoint.Thisexample
*returnsindex=2,whichmeanstheelemntisnotfoundandneedsto
*beinsertedasasecondelement.
*/
intindex=Arrays.binarySearch(sortedArray
if(index<0){
//arrayindicesarezerobased.2indexmeansinsertionpointof
//(2)1=1,soinsertIndex=1
intinsertIndex=index1;
String[]newSortedArray=newString
System.arraycopy(sortedArray,0,newSortedArray
System.arraycopy(sortedArray,insertIndex
newSortedArray,insertIndex
newSortedArray[insertIndex]=toInsert
System.out.println(Arrays.toString(newSortedArray
}
}
http://www.javasuccess.com/bigoquestionsandanswers/

5/7

5/27/2015

BigOnotationquestionsandanswers|JavaSuccess.com

publicstaticvoidmain(String[]args){
insertSortedArray("B");
}
}

So, the decision depends on the usage pattern. Ask yourself


the following questions. Do I have more inserts/deletes or
search? What is the maximum number of elements likely to
be stored in this array? How often do I need the sorted
data? And nally what does my performance benchmark
show?
Q4. How would you choose between a LinkedList and an
ArrayList? PC
A4. It depends on the use case, and the following table
summarizes it.

Big O LinkedList Vs ArrayList

Unless you have lots of inserts in the front and middle and
the performance bench marks clearly shows that LinkedList
is the way to go, it is better to use an ArrayList.

147 total views, 5 views today

Single Pointer: Partitioning around a pivotal number


9 Java Data structures best practices

Posted in Big O notation

http://www.javasuccess.com/bigoquestionsandanswers/

6/7

5/27/2015

BigOnotationquestionsandanswers|JavaSuccess.com

Categories (mobile)
SelectCategory

Reviews
"I have read several technical books over the last few years, but this one was entirely dierent...." - By Meera Subbarao IT Book Zone
Team Leader
I used this to get 6 jobs in 2 weeks -- Vinodh Eth
Broad and insightful. Will raise your exp a few levels even if only half is read . -- by Grant Dawson

Copy righted & disclaimer


The contents in this Java-Success are copy righted. The author has the right to correct or enhance the current content without any
prior notice.
These are general advice only, and one needs to take his/her own circumstances into consideration. The author will not be held
liable for any damages caused or alleged to be caused either directly or indirectly by these materials and resources. Any
trademarked names or labels used in this blog remain the property of their respective trademark owners. No guarantees are made
regarding the accuracy or usefulness of content, though I do make an eort to be accurate. Links to external sites do not imply
endorsement of the linked-to sites.

2015 Java-Success.com

http://www.javasuccess.com/bigoquestionsandanswers/

Responsive Theme powered by


WordPress

7/7

You might also like