Java Interview Code Examples
Filed in: Java
Here are a series of coding interview questions that in my 30 years of experience working for most of the Investment Banks on Wall Street I have encountered. I recommend you try to answer the question first before looking at the Answer. If you can pass all of these you should sail through most coding interviews.
Q.
Write some code that will determine if a given int is a power of 10.
Follow up: Now convert this code so that we can determine if any given n is a power of y ( Generalize the power of 10 base case )
Example: Given the number 10000 is it a power of 10 ? What about 100001 ? For the general case is 7*7*7 a power of 7 what about 7*7*3 being a power of 7 ?
Algorithm: x is a power of y if y multiplied a number of times equals x; so if y=10 then 10*10 and 10*10*10 are both powers of 10.
Answer:
Q:
Given an Array lets call it sortedArray can you use BubbleSort to sort the array in place
What is the Big O complexity
Algorithm: Bubblesort looks at an item in the array compares it to its neighbour if greater than it swaps it
Answer:
Big O complexity is O(n*n) or O(n^2)
Q:
Given a Sorted Array lets call it sortedArray can you write a method binSearch(… ) that given an Element finds it in the array.
Follow up: what is the Big 0 of this algorithm.
Answer:
The big O is O(log n) also note the tail recursion in the solution
Q:
What is Recursion ?
What is tail Recursion ?
How does this affect my stack – give examples using recursion to sum up all the numbers to n ie: sum(3) means 1+2+3 = 6
Answer:
Recursion always has a condition and a call to itself. Tail recursion is last call in method and Compilers optimize this to a loop so you don’t overload the stack. Normal recursion can run out of stack space, so tail is always preferred.
Q:
Write some code to add all the numbers that make up n ie sum(3) = 1+2+3=6, but write this using Java 8 streams.
Follow up what is a reduction ?
Answer:
Reductions are a functional application to apply some logic here a+b the first parameter is 0 because we need to do 0+a as the first apply
Q:
Write recursive algorithms for the following simple use cases - yes Recursion comes up a lot at interviews. SO the most common applications are here:
Fibonacci
Factorial
Euclid Greatest Common Denominator
Answer:
Q:
Given a list reverse the list in place so {10,20,30,40} becomes {40,30,20,10}
Q:
Explain Wait, and sleep with reference to locks and which one gives up its locks when invoked ?
Why do they need to be in Try/Catch blocks ?
What is Synchronized and why do we need it ? Explain race conditions ?
Write your own version of Blocking Q using wait and notify note you cant put data onto a full Q and you cant read data from an empty Q ?
Answer:
Threading 101 semantics need to be explained, plus its important to remember that wait gives up its locks sleep takes them to bed like a cuddly toy when it sleeps.
Sleep/Wait are always in Try/Catch because they throw interrupted exception – you always need to catch this and check if you are interrupted and act appropriately if the interrupt is intended for you.
Synchronized is like a gatekeeper and allows only 1 thread at a time so threads don’t step on each other and change data behind each other’s back – this is essentially a race condition. There are whole books on this subject so I won’t go into detail but read the oracle docs and Concurrency in Practice by Brian Goetz
Here is the code for my version of blocking Q using wait / sleep – note the class does not expose state
Q:
Write a method that checks if a string is a Palindrome without using reverse.
Follow up: do the solution in place
Follow up: loop round the string no more than once so it is efficient
Algorithm: String is a palindrome if it is the same forwards and backwards after removing whitespace.
Answer:
Clean string using regex
Take two ints one at the start i and one at the end j ;
now compare the char in string at i and j if == continue else not palindrome return false;
then i++ and j-- ;
if j > i then we have crossed and we don’t need to go further and if all chars have matched we are palindrome
Q
Write some code that given a string finds the first non repeating character ie: aabb = all characters repeat but aabbc = c is the first non repeating character
Answer:
First create hashmap called hm store all characters as Key and value is a class called CountIndex that stores a) how many times you encounter that character b) the index you found that character at in the string
Now we have a hashmap we go through the string get each char from the string out the map and see if its repeating
If it is non repeating ie count is 1 get the index
Ensure the index is lower than the index of any result because you want the first non-repeating char or use greater than for the last non repeating char
Q
Given this structure
Find the student with the highest average grade ?
Answer:
Firstly you need to explain that you could have more than 1 student returned with the highest average but for simplicity we will just find the first occurrence
You should realize that you probably need a HashMap key=String or Student name Value=Class that stores the cumulative marks and the total number of subjects
The class for the value will have a constructor for creation but to update the class you need an updateSubjectMarks method that takes the mark and adds it to the previous marks and increases the subject
For example Student A has Maths mark 80 and Student A has Physics mark 80 the Constructor gives us Student A mark 80 subject 1 but the update will give us Student A mark 160 subject 2 so Student A’s average is 160/2
With this info the solution is easy create Hashmap; store students – create class if not in Map or Update class if in map; once map is complete; now go through map find highest average by calling each keys Average method.
Q
Given an array of Integers
1. Replace all integers that are evenly divisible by 3 with "fizz"
2. Replace all integers divisible by 5 with "buzz"
3. Replace all integers divisible by both 3 and 5 with "fizzbuzz"
Answer:
Q
How to create a counter class that is Thread safe
Answer:
Q
How to write a thread safe counter class without using Synchronization or thread blocking when two threads update at the same time.
Q
Create a Thread safe stack implementation without using Java locking symantics
Answer:
Q
If I have a resource and I want to limit the number of concurrent accesses to the object how do I do that in Java
Answer:
Java Recursion
Naive Bayes classification AI algorithm
K-Means Clustering AI algorithm
Equity Derivatives tutorial
Fixed Income tutorial
Java
python
Scala
Investment Banking tutorials
HOME

Q.
Write some code that will determine if a given int is a power of 10.
Follow up: Now convert this code so that we can determine if any given n is a power of y ( Generalize the power of 10 base case )
Example: Given the number 10000 is it a power of 10 ? What about 100001 ? For the general case is 7*7*7 a power of 7 what about 7*7*3 being a power of 7 ?
Algorithm: x is a power of y if y multiplied a number of times equals x; so if y=10 then 10*10 and 10*10*10 are both powers of 10.
Answer:
public static boolean pow(int input){
while (input > 9 && input % 10 == 0)
input /= 10;
if(input == 1)
return true;
else
return false;
}
//Generalizing this to use any power
public static boolean pow2(int input, int pow){
while (input > pow-1 && input % pow == 0)
input /= pow;
if(input == 1)
return true;
else
return false;
}
Q:
Given an Array lets call it sortedArray can you use BubbleSort to sort the array in place
What is the Big O complexity
Algorithm: Bubblesort looks at an item in the array compares it to its neighbour if greater than it swaps it
Answer:
Big O complexity is O(n*n) or O(n^2)
public void exch(int j, int jj){
int x=sortedArray[jj];
sortedArray[jj]=sortedArray[j];
sortedArray[j]=x;
}
public void bubbleSort(){
for (int i = 0; i < MAX; i++) {
for (int j = i; j > 0; j--) {
if (sortedArray[j-1] > sortedArray[j])
exch( j, j-1);
else break;
}
}
}
Q:
Given a Sorted Array lets call it sortedArray can you write a method binSearch(… ) that given an Element finds it in the array.
Follow up: what is the Big 0 of this algorithm.
Answer:
The big O is O(log n) also note the tail recursion in the solution
private Optional splitList(int start, int end, int e){
//Calc Midpoint
int mid=Math.abs(end-start)/2 + start;
System.out.println(start+" -> "+ end + " e=" + e + " Middle="+mid);
//Found Element
if(sortedArray[mid]==e){
System.out.println("mid val="+sortedArray[mid]);
return Optional.of(mid);
}
//We have only 1 element and its not the one so Empty or Not Found
if(end-start == 1){
return Optional.empty();
}
//Left or Right
if(e < sortedArray[mid]){
return splitList(start, mid, e);
}else{
//right
return splitList(mid, end, e );
}
}
//Using a binary search algorithm find the element e in the sortedArray[]
public Optional binSearch(int e){
//First iter
int start=0;
int end=sortedArray.length;
//sortedArray is Array at Class Level
return splitList(start, end, e);
}
Q:
What is Recursion ?
What is tail Recursion ?
How does this affect my stack – give examples using recursion to sum up all the numbers to n ie: sum(3) means 1+2+3 = 6
Answer:
Recursion always has a condition and a call to itself. Tail recursion is last call in method and Compilers optimize this to a loop so you don’t overload the stack. Normal recursion can run out of stack space, so tail is always preferred.
public int sum(int n){
if( n >= 1){ //CONDITION
return sum(n-1) + n; //Recurse
}
return n;
}
public int tailSum(int accumulator, int n){
if(n <= 1){ //Condition
return accumulator;
}
//Update Accumulator
//Update Conditional
return tailSum(accumulator + n, n -1); //TAIL as recurse is last item in Method
}
Q:
Write some code to add all the numbers that make up n ie sum(3) = 1+2+3=6, but write this using Java 8 streams.
Follow up what is a reduction ?
Answer:
Reductions are a functional application to apply some logic here a+b the first parameter is 0 because we need to do 0+a as the first apply
public int sumStream(int n){
IntStream stream = IntStream.range(1, n+1);
Integer res=stream.reduce(0,(a,b) -> a+b);
return res;
}
Q:
Write recursive algorithms for the following simple use cases - yes Recursion comes up a lot at interviews. SO the most common applications are here:
Fibonacci
Factorial
Euclid Greatest Common Denominator
Answer:
//Calc n'th fibonacci
public int fibonacci(int n){
if(n <=1 ) { //Condition
return n;
}
//Recurse n-1 + n-2
return fibonacci(n-1) + fibonacci(n-2);
}
//factorial of n
public long factorial ( int n ) {
if(n==1) return 1;
return n * factorial(n-1);
}
/*
* Good test 1440, 408 we would expect 24
* Good test 102, 68 we would expect 34
*
* Largest divisor that divides evenly to both numbers
*
*
*/
public int euclidAlgoGCD(int a, int b){
if(b==0) return a; //if modulo is 0 we have found largest divisor
else return euclidAlgoGCD(b, a % b);
}
Q:
Given a list reverse the list in place so {10,20,30,40} becomes {40,30,20,10}
public class Reverse {
public static void main(String[] args) {
Reverse r = new Reverse();
int[] arr= {10,20,30,40};
r.reverse(arr);
}
private void reverse(int[] arr) {
int length = arr.length;
int t;
for(int i=0; i<length; i++){
//Swap i and length -1; update length; finish if i>=length
if(i>=length){
}
t=arr[length-1];
arr[length-1]=arr[i];
arr[i]=t;
length-=1;
}
for(int k=0; k<arr.length; k++){
System.out.print(arr[k]+" ");
}
}
}
Q:
Explain Wait, and sleep with reference to locks and which one gives up its locks when invoked ?
Why do they need to be in Try/Catch blocks ?
What is Synchronized and why do we need it ? Explain race conditions ?
Write your own version of Blocking Q using wait and notify note you cant put data onto a full Q and you cant read data from an empty Q ?
Answer:
Threading 101 semantics need to be explained, plus its important to remember that wait gives up its locks sleep takes them to bed like a cuddly toy when it sleeps.
Sleep/Wait are always in Try/Catch because they throw interrupted exception – you always need to catch this and check if you are interrupted and act appropriately if the interrupt is intended for you.
Synchronized is like a gatekeeper and allows only 1 thread at a time so threads don’t step on each other and change data behind each other’s back – this is essentially a race condition. There are whole books on this subject so I won’t go into detail but read the oracle docs and Concurrency in Practice by Brian Goetz
Here is the code for my version of blocking Q using wait / sleep – note the class does not expose state
public class MyQ {
private int capacity;
//Store data
List myList ;
public void setup(int capacity){
this.capacity=capacity;
myList = new ArrayList(capacity);
}
public MyQ(){
setup(10);
}
public int getSize(){
return capacity;
}
public synchronized void put(E e ){
while(myList.size()>=capacity){
System.out.println("put Capacity at "+myList.size());
try {
wait();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
myList.add(0,e);
notifyAll();
}
public synchronized E take(){
while(!myList.isEmpty()){
notifyAll();
return myList.remove(0);
}
if(myList.isEmpty()){
System.out.println("take Capacity at "+myList.size());
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
notifyAll();
return myList.remove(0);
}
public synchronized int size() {
return myList.size();
}
public synchronized boolean isEmpty() {
return myList.isEmpty();
}
}
Q:
Write a method that checks if a string is a Palindrome without using reverse.
Follow up: do the solution in place
Follow up: loop round the string no more than once so it is efficient
Algorithm: String is a palindrome if it is the same forwards and backwards after removing whitespace.
Answer:
Clean string using regex
Take two ints one at the start i and one at the end j ;
now compare the char in string at i and j if == continue else not palindrome return false;
then i++ and j-- ;
if j > i then we have crossed and we don’t need to go further and if all chars have matched we are palindrome
public class Pallindrome {
public static void main(String... args) {
Pallindrome p = new Pallindrome();
System.out.println(args[0]);
String s="Dot saw I was Tod";//"racecar ";
if(p.test(s)){
System.out.println(s+" is palindrome");
}else
System.out.println(s+" is not a palindrome");
}
private boolean test(String s) {
String clean = s.replaceAll("\\s+", "").toLowerCase();
int i=0;
int j=clean.length()-1;
System.out.println(clean);
while ( j > i){
if(clean.charAt(i) != clean.charAt(j)){
System.out.println(clean.charAt(i) +" "+ clean.charAt(j));
return false;
}
i++;
j--;
}
return true;
}
}
Q
Write some code that given a string finds the first non repeating character ie: aabb = all characters repeat but aabbc = c is the first non repeating character
Answer:
First create hashmap called hm store all characters as Key and value is a class called CountIndex that stores a) how many times you encounter that character b) the index you found that character at in the string
Now we have a hashmap we go through the string get each char from the string out the map and see if its repeating
If it is non repeating ie count is 1 get the index
Ensure the index is lower than the index of any result because you want the first non-repeating char or use greater than for the last non repeating char
class CountIndex
{
int count,index;
// constructor for first occurrence
public CountIndex(int index) {
this.count = 1;
this.index = index;
}
// method for updating count
public void incCount() {
this.count++;
}
}
class firstNonRpt
{
static final int NO_OF_CHARS = 256;
static HashMap hm = new HashMap(NO_OF_CHARS);
/* calculate count of characters
in the passed string */
static void getCharCountArray(String str)
{
for (int i = 0; i < str.length(); i++)
{
// If character already occurred,
if(hm.containsKey(str.charAt(i)))
{
// updating count
hm.get(str.charAt(i)).incCount();
}
// If it's first occurrence, then store the index and count = 1
else
{
hm.put(str.charAt(i), new CountIndex(i));
}
}
}
/* The method returns index of first non-repeating
character in a string. If all characters are repeating
then returns Integer.MAX_VALUE */
static int firstNonRepeating(String str)
{
getCharCountArray(str);
int result = Integer.MAX_VALUE, i;
for (i = 0; i < str.length(); i++)
{
// If this character occurs only once and appears
// before the current result, then update the result
if (hm.get(str.charAt(i)).count == 1 && result > hm.get(str.charAt(i)).index){
System.out.println(result);
result = hm.get(str.charAt(i)).index;
}
}
return result;
}
// Driver method
public static void main (String[] args)
{
String str = "aabb";
int index = firstNonRepeating(str);
System.out.println(index == Integer.MAX_VALUE ? "Either all characters are repeating " +
" or string is empty" : "First non-repeating character is " + str.charAt(index));
}
}
Q
Given this structure
String s[][] = {{"jerry","65"},
{"bob","91"}, {"jerry","23"}, {"Eric","83"},{"Eric","99"}};
Find the student with the highest average grade ?
Answer:
Firstly you need to explain that you could have more than 1 student returned with the highest average but for simplicity we will just find the first occurrence
You should realize that you probably need a HashMap key=String or Student name Value=Class that stores the cumulative marks and the total number of subjects
The class for the value will have a constructor for creation but to update the class you need an updateSubjectMarks method that takes the mark and adds it to the previous marks and increases the subject
For example Student A has Maths mark 80 and Student A has Physics mark 80 the Constructor gives us Student A mark 80 subject 1 but the update will give us Student A mark 160 subject 2 so Student A’s average is 160/2
With this info the solution is easy create Hashmap; store students – create class if not in Map or Update class if in map; once map is complete; now go through map find highest average by calling each keys Average method.
class avgStudent {
int mark=0;
int subjects=0;
int avg=0;
public avgStudent(int mark) {
this.mark = mark;
this.subjects ++;
}
public void updateSubjectsMarks(int mark){
this.mark+=mark;
this.subjects++;
}
public double getavg(){
return mark/subjects;
}
}
public class Student {
public static void main(String[] args) {
String s[][] = {{"jerry","65"},
{"bob","91"}, {"jerry","23"}, {"Eric","83"},{"Eric","99"}};
Map sMap = new HashMap();
for(int i=0; i<s.length; i++){
String name=s[i][0];
int mark = Integer.parseInt(s[i][1]); // Warning can throw num format exception
if(sMap.containsKey(name)){
avgStudent avgStud = sMap.get(name) ;
avgStud.updateSubjectsMarks(mark);
}else{
//if not in map
sMap.put(name, new avgStudent(mark));
}
}
// in map show map
double avg=0.0;
String res="";
for( String k : sMap.keySet()){
System.out.println(k+" " + sMap.get(k).getavg() + " " + sMap.get(k).mark+ " "+ sMap.get(k).subjects);
if(sMap.get(k).getavg() > avg){
avg=sMap.get(k).getavg();
res=k;
}
}
System.out.println("Highest ="+res);
}
}
Q
Given an array of Integers
1. Replace all integers that are evenly divisible by 3 with "fizz"
2. Replace all integers divisible by 5 with "buzz"
3. Replace all integers divisible by both 3 and 5 with "fizzbuzz"
Answer:
public class FizzBuzz {
public static String fizzBuzz(int number) {
if (number % 3 == 0) {
if (number % 5 == 0) {
return "fizzbuzz";
} else {
return "fizz";
}
} else if (number % 5 == 0) {
return "buzz";
}
return String.valueOf(number);
}
public static void main(String[] args) {
int[] num = {15,30,7,6,3,5,6};
for(int i=0; i<num.length; i++){
System.out.print(fizzBuzz(num[i])+" ");
}
}
}
Q
How to create a counter class that is Thread safe
Answer:
public final class Counter {
private long value = 0;
public synchronized long getValue() {
return value;
}
public synchronized long increment() {
return ++value;
}
}
//You could just use AtomicInteger but this demonstrates simple thread safety
Q
How to write a thread safe counter class without using Synchronization or thread blocking when two threads update at the same time.
public class NonblockingCounter {
private AtomicInteger value;
public int getValue() {
return value.get();
}
public int increment() {
int v;
do {
v = value.get();
}
while (!value.compareAndSet(v, v + 1));
return v + 1;
}
}
Q
Create a Thread safe stack implementation without using Java locking symantics
Answer:
public class ConcurrentStack{
AtomicReference> head = new AtomicReference >();
public void push(E item) {
NodenewHead = new Node (item);
NodeoldHead;
do {
oldHead = head.get();
newHead.next = oldHead;
} while (!head.compareAndSet(oldHead, newHead));
}
public E pop() {
NodeoldHead;
NodenewHead;
do {
oldHead = head.get();
if (oldHead == null)
return null;
newHead = oldHead.next;
} while (!head.compareAndSet(oldHead,newHead));
return oldHead.item;
}
static class Node{
final E item;
Nodenext;
public Node(E item) { this.item = item; }
}
}
Q
If I have a resource and I want to limit the number of concurrent accesses to the object how do I do that in Java
Answer:
public class ResourceLimiter {
private Semaphore sem ;
public ResourceLimiter(int permits) {
sem= new Semaphore(permits, true);
}
public boolean getPermit(){
return sem.tryAcquire();
}
public void releasePermits(){
sem.release();
}
public int availablePermits(){
return sem.availablePermits();
}
public static void main(String[] args){
try {
int permits=10;
ExecutorService executorService = Executors.newFixedThreadPool(permits);
ResourceLimiter limiter = new ResourceLimiter(permits);
IntStream.range(0, permits).forEach(i -> executorService.submit(limiter::getPermit));
Thread.currentThread();
Thread.sleep(1000); // Wait for exector to do the work
System.out.println("All permits should be taken "+limiter.availablePermits());
IntStream.range(0, permits).forEach(i -> executorService.submit(limiter::releasePermits));
Thread.currentThread();
Thread.sleep(1000); // Wait for exector to do the work
System.out.println("All permits should be released "+limiter.availablePermits());
executorService.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
People who enjoyed this article also enjoyed the following:
Java Recursion
Naive Bayes classification AI algorithm
K-Means Clustering AI algorithm
Equity Derivatives tutorial
Fixed Income tutorial
And the following Trails:
C++Java
python
Scala
Investment Banking tutorials
HOME
