Javarevisited: Top 30 Programming questions asked in Interview – Java C C Answers

4 programming

Javarevisited

Blog about Java programming language, FIX Protocol, Tibco RV

Top 30 Programming questions asked in Interview – Java C C++ Answers

Programming questions are an integral part of any Java or C++ programmer or software analyst interview. No matter on which language you have expertise it’s expected that you are familiar with fundamental of programming and can solve problems without taking help of API. Programming questions like reversing String using recursion or How to find if Array contains duplicates are some popular examples of programming question in Java. Programming questions present lot of challenges Especially to Java developers as compared to C++ programmer and I think, One reason for this is powerful Java API; Which has method for almost every need and you rarely need to write by your own or there are lots of third party library from Apache, Spring, Google and other open source.

These programming interview questions are from my personal collections and I have only chosen those which are not very difficult, can be solved easily but at the same time can become too complex or confusing, present lots of follow-up questions and test fundamentals of programming, OOPS and design.

String Programming Interview Questions

1) Write code to check a String is palindrome or not? (solution)

Palindrome are those String whose reverse is equal to original.This can be done by using either StringBuffer reverse() method or by technique demonstrated in the solution here.

2) Write a method which will remove any given character from a String? (solution)

hint : you can remove a given character from String by converting it into character array and then using substring() method for removing them from output string.

3) Print all permutation of String both iterative and Recursive way? (solution)

4) Write a function to find out longest palindrome in a given string? (solution)

5) How to find first non repeated character of a given String? (solution)

6) How to count occurrence of a given character in a String? (solution)

7) How to check if two String are Anagram? (solution)

8) How to convert numeric String to int in Java? (solution)

Some more String related Questions which mostly appear in Java programming interviews:

Main difference is that String is immutable but both StringBuilder and StringBuffer are mutable. Also StringBuilder is not synchronized like StringBuffer and that’s why faster and should be used for temporary String manipulation.

2) Why String is final in Java? (answer)

String is final because of same reason it is immutable. Couple of reasons which I think make sense is implementation of String pool, Security, and Performance. Java designers knows that String will be used heavily in every single Java program, so they optimized it from the start.

Java API provides several convenient methods to split string based upon any delimiter e.g. comma, semi colon or colon. You can even use regular expression to split a big string into several smaller strings.

Programming questions on Array

9) In an array 1-100 numbers are stored, one number is missing how do you find it? (solution)

10) In an array 1-100 exactly one number is duplicate how do you find it? (solution)

11) In an array 1-100 multiple numbers are duplicates, how do you find it? (solution)

One trick in this programming questions is by using HashMap or Hashtable , we can store number as key and its occurrence as value, if number is already present in Hashtable then increment its value or insert value as 1 and later on print all those numbers whose values are more than one.

12) Given two arrays, 1,2,3,4,5 and 2,3,1,0,5 find which number is not present in the second array.

Here is a quick tip to solve this programming question: put the elements of the second array in the Hashtable and for every element of the first array, check whether it’s present in the hash or not, O/P all those elements from the first array that are not present in the hash table

13) How do you find second highest number in an integer array? (solution)

14) How to find all pairs in array of integers whose sum is equal to given number? (solution)

15) How to remove duplicate elements from array in Java? (solution)

16) How to find largest and smallest number in array? (solution)

17) How to find top two maximum number in array? (solution)

LinkedList Programming Interview Questions

To answer this programming question I would say you start with simple solution on which you traverse the LinkedList until you find the tail of linked list where it points to null to find the length of linked list and then reiterating till middle. After this answer interviewer will ask you find the middle element in single pass and there you can explain that by doing space-time trade-off you can use two pointers one incrementing one step at a time and other incrementing two step a time, so when first pointer reaches end of linked second pointer will point to the middle element.

This programming question is similar to above and can be solved by using 2 pointers, start second pointer when first pointer reaches third place.

16) How do you find if there is any loop in singly linked list? How do you find the start of the loop? (solution)

This programming question can also be solved using 2 pointers and if you increase one pointer one step at a time and other as two steps at a time they will meet in some point if there is a loop.

17) How do you reverse a singly linked list? (solution)

18) Difference between linked list and array data structure? (answer)

Binary Tree Programming Interview Questions

18) How do you find depth of binary tree?

19) Write code to print InOrder traversal of a tree?

20) Print out all leaf node of a binary tree?

21) Write a method in Java to check if a tree is a binary search tree or not?

Programming Questions on Searching and Sorting

23) Write a program to sort numbers in place using quick sort ? (solution)

24) Write a program to implement binary search algorithm in Java or C++? (solution)

25) How do you sort Java object using Comparator? (answer)

This is another Java specific programming questions and you can check how to sort Object using Comparator and Comparable for answer.

27) Write code to implement Bubble Sort in Java? (solution)

Programming Questions on Numbers

26) Write code to check whether a no is power of two or not? (solution)

27) Write a program to check whether a number is palindrome or not? (solution)

Check out this post which shows how to reverse number in Java and can be used to find if its palindrome or not.

28) Write code to check whether an integer is Armstrong number or not? (solution)

Here is a Java program to find Armstrong number, you can use same logic to write code in any other programming language like C and C++.

29) Write a program to find all prime number up to a given numbers? (solution)

Here is another Java program to find prime numbers and print them. By using logic demonstrated in this program; you can write similar program in C and C++.

30) Write function to compute Nth Fibonacci number? Both iterative and recursive? (solution)

Check this Java program to print Fibonacci Series using recursion and iteration.

31) How to check if a number is binary? (solution)

For this question, you need to write a function which will accept an integer and return true if it contains only 0 and 1 e.g. if input is 123 then your function will return false, for 101 it should return true.

33) How to count number of set bits in given integer? (solution)

34) How to find sum of digits of a number using recursion? (solution)

35) How to swap two numbers without using temp variable? (solution)

36) How to find largest of three integers in Java? (solution)

37) Write a program to find prime factors of integer? (solution)

38) How to add two integer without using arithmetic operator? (solution)

General Programming Interview Questions

32) You need to write a function to climb n steps you can climb either 1 step at a time or 2 steps a time, write a function to return number of ways to climb a ladder with n step.

33) Write code for Generate Random No in a range from min to max?

34) Write program for word-wrap which should work on any screen size?

35) Design an algorithm to find the frequency of occurrence of a word in an article?

36) Write a program to implement blocking queue in Java?

37) Write a program for producer-consumer problem? (solution)

This article solves producer consumer problem using BlockingQueue in Java. You can refer it to answer this question.

Books to prepare for Programming Job Interviews

This is the must read book, if you are preparing for Google interview, or something along the line e.g. Facebook, Amazon or Microsoft Interviews. It contains top 10 programming problems, frequently asked at Google with detailed worked out solution, explanation in both pseudo code and in C++.

Tips on answering Programming questions

2. If you write iterative version of function then Interviewer may ask you to write recursive version or vice-versa so be prepare for that.

3. If you write a recursive function then Interviewer will ask to optimize it, even in case of Iterative version. So remember that you can optimize recursive function by Memorization (caching already calculated value) and by applying some space/time tradeoff principle. For example recursive version of Fibonacci series has O(n2) which can be reduced to O(n) using Memoziation.

4. Interviewer may ask you to calculate Order of complexity for best and worst case of any method so be prepared.

5. Most of the time Interviewer ask how to fix a problem as follow-up question e.g. he will ask how do you find deadlock and then how to fix deadlock in java etc.

61 comments:

very nice collection of programming interview questions would have been much better if you provided full answers of these programming interview question, nevertheless quality of these programming interview question is quite good and its really challenging for first timer.

Thanks for your comments guys, good to know that you like these programming interview questions and find useful. I suggest to contribute on this with some unique programming questions you faced during interviews.

How would you implement a queue using two stacks?

How would you implement a Singleton in c++? (never heard of it before, so challenging)

Agree with you Anonymous, these programming questions can be very challenging to solve in limited time if faced first time. that's why we need to prepare for programming interview questions also.

Nice questions you can include the following

can anyone help me solve this program for me;

write a java program that prompts the user to to 20 characters, count the occurrences of the same element in the array. Display the repeated elements and its occurrences. Please i need to solve this asap.. email me syakir_aznan@yahoo.com

can you also share programming job interview question for junior position ? I am preparing puzzles interview questions, Data structure interview questions but also want to have a look on java question not difficult and suitable for upto 2 years of experience.

The sad thing about programming questions on interviews is that a lot of them focus on error conditions caused by bad java programming. I programmed in Java for over 10 years and I am a very good Java programmer. I am not good at interview tests that focus on those types of bad programming because they never really come up in the real world of Java programming. Once you instinctively do things right for years and years you rarely focus on things you never do as a programmer. You will not spend your programming career on these strange minutia type issues that come up on programming tests. Sometimes I get hung up on the approach a question has to a programming problem because they sometimes don't start from a good OO point of view to begin with. They hurt my head because I have over a decade of doing things right and I don't focus on doing things wrong! And very few developers do a lot of threading. I've done some threading and you never assume you know what threading code will do by looking at ink on paper. You are testing your threading in a IDE and making sure it is doing what you expect. Coding tests on interviews will not find the best programmers that is for sure. Just someone who studied for them.

@Anonymous, I agree with you most of programming interviews ask thing which has nothing to do with the job you are going to perform. they look for excellent multi-threading or programming aptitude but what you never going to write true concurrent code there or complete new program.

Recursive version of Fibonacci series is actually 2^n, not O(n2).

The dialog box will be centered over the component given in the first parameter.

Typically you would give the window over which it should be centered.

If your program doesn't have a window, you may simply write null,

in which case the dialog box will be centered on the screen.

There is a very good book called "programming exposed interview". Its just fantastic, you can get answers of some of programming questions mentioned here and explanation is simply fantastic.

2) Write Java program for breadth first and depth first traversal.

3) Several good programming interview questions on Spring, trees and linked list and most importantly puzzles.

On question 10, your single pass solution is really the same as your two pass solution. Even if you take turns incrementing the two pointers, you are still passing through the list 1.5 times.

A comment on Question 12 (finding a loop in a singly linked list): The proposed solution certainly determines in linear time whether there is a loop, but it doesn't find the starting place of that loop. For that, I think we have to use the naive solution: keep a hash table of previously visited nodes and see if we get a duplicate.

Excuse me sir. we are following ur blog to understand something not getting confusion. Write in such a way that someone can remove his/her doubt rather than getting so much confusion. I think what I want to say u can understand. Thanks.

@Anonymous,Sorry I didn't get your point? These programming question are for practice before appearing to interviews? Are you complaining about answers of these question? If yes than you can easily find all answers by little work. The scope of this post is to cover programming related questions. I have even covered some of these questions in details like Reversing String using recursion etc.

You can solve the missing member problem by subtracting the sum of the shorter list from the longer.

I find it strange that I can solve most of these problems and I'm in my first year of studying Computer Science.

Very very great post. About 6 out of these 30 questions were asked to me in a test. But I found it very hard to make some logic and write code on a paper because I was used to do programming on computer. Can anyone tell me that whether this problem is only with me or every one finds it difficult to code on a paper.

In reply to Tim!

Dear you might be a good programmer but, in my opinion, every programmer can solve these problems if there is no time limitation. Actual thing is to solve any given problem within time and in the tense environment of an interview.

Here is solution for 5) which use simple arrays operation and never use collection like HashSet

5) In an array 1-100 numbers are stored, one number is missing how do you find it?

totalnumber = 100, a is that array,complexity O(n)

use HashSet O(n x log n)

int b[]=new int[totalnumber];

for (int j=0;j<totalnumber;j++) <

8)Given two arrays, 1,2,3,4,5 and 2,3,1,0,5 find which number is not present in the second array.

* use native array way: find max element in second[] and first[], defined an array third[max]

* iterate second[] , use the element as index of third[] and let third[elementofsecond]=1

* iterate first[] if third[elementOffirst]==0, this is the element which is not present in

Complexity is O(n+m)

int max = first[0];

for (int i=0;i<first.length;i++) <

if (max<first[i]) max=first[i];

for (int i=0;i<second.length;i++) <

if (max<second[i]) max=second[i];

int third[] = new int[max+1];

int result[] = new int[first.length+second.length];

for (int i=0;i<second.length;i++) <

for (int i=0;i<first.length;i++) <

if (third[first[i]]==0) result[k++]=first[i];

if (k==0) return new int[0];

int finalResult [] = new int [k];

for (int i=0;i<k;i++) finalResult[i] = result[i];

> 2) Write a method which will remove any given character from a String?

> 3) Print all permutation of String both iterative and Recursive way?

> 4) Write a function to find out longest palindrome in a given string?

8)Given two arrays, 1,2,3,4,5 and 2,3,1,0,5 find which number is not present in the second array.

2. Marching two sorted array to find those duplicate numbers.

Most of them are too easy. . really. just in class 11 but i no most of these. some of them have also been in question paper.

8)Given two arrays, 1,2,3,4,5 and 2,3,1,0,5 find which number is not present in the second array.

for (int i = 0; i < a.length; i++) <

for (int j = 0; j < b.length; j++) <

System.out.println("Not Present" + a[i]);

great stuff,, but it would be much better if the answer were given here.

CAN ANYONE SEND ME SOLUTION OF ABOVE GIVEN QUESTION PLEASE. rajnikantmrc@gmail.com

Write the code you can get it on the greatest common factor.please any one answer this question

Hello Javin, would you mind to share some Programming Interview questions from Microsoft, Google, Amazon, Twitter and Facebook. I have those companies on my radar and preparing for their job interviews. Since you share some genuine, real questions, I would be glad if you can get something from your network for Microsoft, Amazon and Google. I am specially interested on coding, logic and programming interviews, but you can also share SQL, UNIX questions and puzzles.

When trying to solve the question asking "Given two arrays, 1,2,3,4,5 and 2,3,1,0,5 find which number is not present in the second array" I see a lot of O(n^2) responses (double loops). I think knowing the API gives a good developer a 'leg up':

Set setA = new HashSet<>(Arrays.asList(a));

Set setB = new HashSet<>(Arrays.asList(b));

5) In an array 1-100 numbers are stored, one number is missing how do you find it?

First decision sort and walk. Fast algorithm formula: result = sum(1..100) – sum(of array numbers).

35) You need to write a function to climb n steps you can climb either 1 step at a time or 2 steps a time, write a function to return number of ways to climb a ladder with n step.

Enjoy C/C++ http://slorents.blogspot.com.au/2013/11/climb-ladder-with-n-step.html

8)Given two arrays, 1,2,3,4,5 and 2,3,1,0,5 find which number is not present in the second array.

Because <1,2,3,4,5>is sorted array you can use binary search in it while walk through <2,3,1,0,5>. It is fastest, isn't it?

plz give solution using java programmin to find or count super palindrome in a string eg.nanded . ie nan is

palindrom and ded is another palindrome ..plz mail soln to koolkbh@rediffmail.vom

For computing fibonacci sequence numbers, you can even manage a O(log(n)) complexity (in time), same for question number 25 (mistakenly written as 35 by the way).

can you give me the code for

Q)Biggest polidrome in a given string?

can you add some programming interview questions on multithreading concept?

Here's one I got:

why don't you put list of complex programming questions for interview

Coding on a whiteboard, without a computer, without tools to debug or observer your working code, without a search engine, observed and critiqued is really unnatural. What's the point again? To see how good someone is at programming?

8)Given two arrays, 1,2,3,4,5 and 2,3,1,0,5 find which number is not present in the second array.

How to convert String s=" Hi Hello World" into "world hello hi" can you please tell me

Can any one help me in doing this Program:

Design a Java Program to generate a bill for a customer after his order had been taken in any of the Pizza hut outlets

String a = "My name is X Y Z";

newString = newString + a.charAt(j);

@Stanislav Lorents: your solution for the step count is wrong. For one step, there's one way (s(1) = 1). For two steps, two ways (s(2) = 2). From the third step, you can choose to go to step 1 or 2. The number of ways is s(1) + s(2). For four steps, you can go to step 3 or 2 (s(3) + s(2) ways). It's Fibonacci again.

Great collection and thank you for sharing, I must admit few of these I never encountered.

But I must say that I disagree with your statement:

"it’s expected that you are familiar with fundamental of programming and can solve problems without taking help of API"

With first part I agree, but the second part. doesn't that just sound strange to you?

I read it like this: "It is expected from you to reinvents the wheel, to not follow best practices, to make code maintainability and readability more difficult?

The point of these tests are to check your fundamentals and simply to check if you can write code. For example no one will ever expect from you to write your own reverse string implementation, but reversing something is a common task and by doing this you show that you can code it out.

Nevertheless thanks again for sharing and if interested here are some additional tests, I hope you like them.

For a better solution for question 8, assuming it's consecutive numbers up to N, return N*(N+1)/2 – sumOfMissingNoArray.

can you help me for writing this program

//In an array 1-100 numbers are stored, one number is missing how do you find it?

1) ( In java or unix ) Split the input file based on number of columns, each output file should have only column. can anybody able to solve this.

2. Write a program to evaluate a mathematical expression given in string format without using inbuilt eval() function. For example input would be a string variable of the form 5*10/20+6 and your program should output the result. The challenge here is first you have the input in string format and secondly you got to follow the BODMAS rules.

InterView Programming Problems topic wise

//Two circles are given (center and radius for each). One circle is bigger than the other. write a program to find out the smaller circle is completely inside the bigger one. if the smaller circle is inside the bigger one, print yes, otherwise print No

using namespace std;

if((r1-r2)>(distance))// circle is inside if distance is lessthan difference between radius

How to print this patter:-

Removing repeated number 121 and 122.

Since 121 has two 1's llly 122 has two 2's. Any one suggest me

matrix program accept matrix size by user

Thanks for sharing this list of interview questions.

Just amazing. It covers almost all the major questions.

4.Write a function to find out longest palindrome in a given string

public static void main(String[] args) <

public static String longestPalindrome(String s)

Leave a Reply

Your email address will not be published. Required fields are marked *