Apr 14, 2014

Understanding Big O notations through Java examples

Q. Have you seen job advertisements requiring Java candidates to work in real-time or high volume transaction processing systems?

If you are applying for such jobs, you can be quizzed on Big O notation. Here are some basics to brush up on.

Big-O gives you the upper bound. For example, if you need to search an element in an array and you expect the array to be large, you might just say that you opt for a binary search instead of a sequential scan because the former has O(log n) complexity wheres the latter has O(n) complexity.

Big-O

Description/Example

If n=10, and c=2

If n=20, and c=2

O(1)
Constant

Running time is constant.

Determining if a String is equal to a given value

if(str.equals("java"))
{
return true;
}
else {
return false;
}

A Map look up by key -- map.get(key);

1

1

O(log n)

Logarithmic

Running time increases logarithmically in proportion to the input size.

Finding an item in a sorted array with a binary search

For example, search for 2 in a list of numbers 1,2,3,4,5,6,7

Step 1: Sort the data set in ascending order as binary search works on sorted data.

Step 2: Get the middle element (e.g. 4) of the data set and compare it against the search item (e.g. 2), and if it is equal return that element

Step 3: If search item value is lower, discard the second half of the data set and use the first half (e.g. 1,2,3). If the search item value is higher, then discard the first half and use the second half (e.g. 5,6,7)

Step 4: Repeat steps 2 and 3 until the search item is found or the last element is reached and search item is not found.