Thursday, April 13, 2023

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

Top 30 Programming interview questions
Programming questions are an integral part of any Java or C++ programmer or software analyst interview. No matter which language you have the expertise it’s expected that you are familiar with the fundamentals of programming and can solve problems without taking the 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 a 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 a 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 sources.

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.

I have not given answers to these programming questions but those can be found by Google and I will try to post links of answers here sometime later but at the same time, I will try to provide quick tips or hints on some questions.

Anyone who is following programming questions must be familiar with these questions and also knows the answer for most of these but for new guys and even for intermediate it's worth refreshing it before going to any programming job interview like Core Java interview.

Also, basic knowledge of essential data structure and algorithms is also very important and that's why I suggest all Java programmers join a comprehensive Data Structure and Algorithms course like Data Structures and Algorithms: Deep Dive Using Java on Udemy to improve your knowledge and algorithms skills.




1. String Programming Interview Questions

The string is a primary and probably most common thing you come across on any programming language and so is with any programming interview. There is almost always a question on String whether its related to the length or replace but I have always found one or two String programming questions on interviews.


1) Write code to check a String is palindrome or not? (solution)
A palindrome is those String whose reverse is equal to the 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 a 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 the first non repeated character of a given String? (solution)


6) How to count the 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:

1) What is the difference between String, StringBuilder, and StringBuffer in Java? (answer)
The 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)
The string is final because of same reason it is immutable. Couple of reasons which I think make sense is an implementation of String pool, Security, and Performance. Java designers know that String will be used heavily in every single Java program, so they optimized it from the start.

3) How to Split String in Java? (answer)
Java API provides several convenient methods to split a string based upon any delimiter e.g. comma, semicolon or colon. You can even use a regular expression to split a big string into several smaller strings.

4) Why Char array is preferred over String for storing password? (answer)


These questions help improve your knowledge of string as a data structure. If you can solve all these String questions without any help then you are in good shape.

If you want to learn more about String and other data structure then I suggest you check out the Master the Coding Interview: Data Structures + Algorithms course by Andrei Negaoie on ZTM Academy. It's a great course to revise fundamentals before interview. 

Data Structure and Algorithm Interview Questions Programmers

If you need more practice, here is another list of 20 string coding questions.




2. Programming questions on Array

An array is one of the topics where most of the programming questions are asked. There are many and many programming questions on Array and here I have included only some of them which are not very difficult to solve but some of the array programming questions can be extremely challenging, so well prepare this topic.


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 a number as key and its occurrence as a value if the 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 the second highest number in an integer array? (solution)


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


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


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


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


These questions will not only help you to develop your problem-solving skills but also improve your knowledge of array data structure.

If you need more advanced questions based upon array then you can see also see The Coding Interview Bootcamp: Algorithms + Data Structures, a bootcamp style course on algorithms, especially designed for interview preparation to get a job on technical giants like Google, Microsoft, Apple, Facebook etc.



And, if you feel 10 is not enough questions and you need more practice, then you can also check out this list of 30 array questions.




3. LinkedList Programming Interview Questions

A linked list is another important data structure after array and String. It actually compliments array and whatever you cannot do with an array, you can do with a linked list.

For example, the array needs contiguous memory to store objects but the linked list doesn't need that. It's difficult to add and remove elements in an array because you need to shift existing elements but that is very easy with a linked list, as you just need to change the pointer to accommodate them.

But, nothing is free in this world. While linked list provides all these functionalities but the cost of that you lose the ability to search elements in constant time with index. Searching and element require traversing linked list, which means examining all nodes, thus cost around O(n) time.


14) How do you find middle element of a linked list in a single pass?
To answer this programming question I would say you start with a 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 the linked list and then reiterating till middle.

After this answer interviewer will ask you to 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 the first pointer reaches end of linked second pointer will point to the middle element.



15) How do you find the 3rd element from last in a single pass? (solution)
This programming question is similar to above and can be solved by using 2 pointers, start the second pointer when the first pointer reaches third place.


16) How do you find if there is any loop in a 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 a linked list and array data structure? (answer)



If you are having trouble solving these linked list coding questions then I suggest you refresh your data structure and algorithms skill by going through  Grokking the Coding Interview: Patterns for Coding Questions course on Educative, one of the best course to learn coding patterns like Sliding Window and Merge intervals, which can be used to solve 100+ Leetcode problems. 

Programming Interview Questions with 1 to 3 years experienced programmers



If you need more linked list based questions then you can also check out this list of 30 linked list interview questions for more practice questions.



4. Binary Tree Programming Interview Questions

Binary tree or simply tree is one of favorite topic for most of the interviewer and pose a real challenge if you struggle with recursion. Programming questions on the tree can become increasingly difficult when you think iterative but sometimes can be very easy if you come with a recursive solution.


18) How do you find the depth of a binary tree? (solution)


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


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


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


22) How to check if a tree is balanced or not in Java? (solution)


23) How is a binary search tree implemented? (solution)

24) How do you perform preorder traversal in a given binary tree? (solution)

25) How do you traverse a given binary tree in preorder without recursion? (solution)

26) How do you print all nodes of a given binary tree using inorder traversal without recursion? (solution)
27) How do you implement a postorder traversal algorithm? (solution)
28) How do you traverse a binary tree in postorder traversal without recursion? (solution)
29) How are all leaves of a binary search tree printed? (solution)
40) How do you count a number of leaf nodes in a given binary tree? (solution)
41) How do you perform a binary search in a given array? (solution)


Binary tree based questions sometimes get trick and if you are having trouble solving these tree-based list coding questions then I suggest you revise your data structure and algorithms skill by going through Software Engineering Interview Course on Exponent.  


Top 30 Coding questions asked in Interview - Java C C++ Answers


This course provides a comprehensive review of the most important data structures, algorithms, and system design principles and also provides mock interviews with FAANG engineers and managers showcasing what interviews look like, as well as interactive coding problems in Python and JavaScript. 

Plus, there are extra lessons on behavioral interview questions for engineers, and advice on growing your tech career.  It's written by an ex-FAANG engineers and it is one of the most comprehensive course to revise all important data structures like an array, linked list, binary tree etc.



5. Programming Questions on Searching and Sorting

I have only included two programming questions related to searching and sorting but there are more can be found on Google. Purpose of these programming questions is to see whether a programmer is familiar with the essential search and sort mechanism or not.


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


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


25) How do you sort Java objects using a Comparator? (answer)
This is another Java specific programming questions and you can check how to sort Object using Comparator and Comparable for an answer.

26) Write code to implement Insertion Sort in Java? (solution)


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



If you can solve these questions easily then you are in good shape. For more advanced questions, I suggest you solve problems given in the Algorithm Design Manual by Steven Skiena, a book with the toughest algorithm questions.

Top 30 Algorithms questions asked in Interview - Java C C++ Answers




6. Programming Questions on Numbers

Most of the programming questions are based on numbers and these are the ones which most of us did on the college level and mind you they still have value I have seen programmers with experience of 3 years struggle with these programming questions and doesn't solve it some time and take a lot of time which simply shows that they are not in programming in there day to day work.


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


27) Write a program to check whether a number is a palindrome or not? (solution)
Check out this post which shows how to reverse a 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 the 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 number? (solution)
Here is another Java program to find prime numbers and print them. By using logic demonstrated in this program; you can write a similar program in C and C++.


30) Write a function to compute Nth Fibonacci number? Both iterative and recursive? (solution)
You can 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 the input is 123 then your function will return false, for 101 it should return true.

32)  How to reverse an integer in Java? (solution)


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


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


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


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


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


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


If you need more such coding questions you can take help from books like Cracking the  Coding Interview book by Gayle Lakman  McDowell which presents 189+ Programming questions and solution. A good book to prepare for programming job interviews in a short time.


Top 30 Programming Interview Questions Answers for Programmers




7. General Programming Interview Questions

In this category of programming questions, I have put questions which are not fit into any data structure but present a real-life problem and you need to provide a solution. These programming questions are sometimes based on problems faced by the developer itself.

I have not included many Software design-related programming question which I have shared on Top 20 software design questions and answers; you can also check that.


31) Write a program to find out if two rectangles R1 and R2 are overlapping? (solution)


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 a number of ways to climb a ladder with n step. (solution)
It's actually a Fibonacci series so you can solve it like that.

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


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


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


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


37) Write a program for the producer-consumer problem? (solution)
This article solves the producer-consumer problem using BlockingQueue in Java. You can refer it to answer this question.


8. Books to prepare for Programming Job Interviews

There are a lot of good books available, which can help the programmer to do well on Interviews. Here is a list of books, which I personally prefer, in order, I like them.

Programming Interview Questions and Answers

A must-read books for both beginners and experienced programmers alike. It not only help you to do well on interviews but also on negotiation, answering general questions etc.
This book contains a collection of questions from a wide range of programming topics, including data structure, algorithms, strings, Java, networking, database, SQL, object-oriented programming, software design etc. This book will give you the whole picture of what can be asked.


3. Top 10 coding interview problems asked in Google with solutions: Algorithmic Approach

This is the must read a 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 a solution, explanation in both pseudocodes and in C++.



9. Tips on answering Programming questions

Interviews are not ready and even if you know the answers you need to keep some things in mind while answering the questions or solving problems. The interviewer often likes to see your ability to solve unknown problems and how you react when a new challenge presented.

For example, if you wrote a recursive solution then they will ask you to solve without recursion, if you use additional memory then you will ask you to solve without that and in-place, mostly in case of an array and linked list problems.

Here are some of the tips to do well on your programming interview:

1. If Interviewer asks you to write function then make sure you do some necessary check for bad input e.g. null check or empty check. Most of the time programmer forgets to test for not null, empty, less than 1, greater than 1 or zero input.


2. If you write an iterative version of function then Interviewer may ask you to write recursive version or vice-versa so be prepared 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(n ^2) time performance which can be reduced to O(n) using Memoziation.


4. The 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.


These are just some of the tips you can follow to be successful in you programming Job interviews. As I told, it's not enough just answering the questions, you need to be attentive and see how the interviewer is reacting. Is he getting pleased with your approach you are not irritating him off by asking silly questions, you need to be attentive to your surrounding?

If you are a fresher or a junior developer and haven't had much programming job interview experience, I suggest you go through Grokking Modern System Design for Software Engineers & Manager course on Educative. One of the best course to master one of the toughest topic on Programming interview, System Design.   




Apart from these programming interview questions  you can also checkout these 25 Software Design questions and some of the other Java programming questions I have already discussed in my blog. 

You can also take help from  Programming Interviews Exposed and Cracking the Coding Interview book with a solution to prepare for any programming Job interview. Those two books have helped me a lot in the past and even today I read them whenever I need to refresh my concepts.



10. Now You’re Ready for the Programming Interview

These are some of the most common questions outside of data structure and algorithms that help you to do really well in your interview.

I have also shared a lot of these questions on my blog, so if you are really interested, you can always search for them.

These common coding, data structure, and algorithm questions are the ones you need to know to successfully interview with any company, big or small, for any level of programming job.

If you are looking for a programming or software development job, you can start your preparation with this list of coding questions.

This list provides good topics to prepare and also helps assess your preparation to find out your areas of strength and weakness.

As I said before, a good knowledge of data structure and algorithms is important for success in coding interviews and that’s where you should focus most of your attention.



Closing Notes
Thanks, You made it to the end of the article … Good luck with your programming interview! It’s certainly not going to be easy, but by following this roadmap and guide, you are one step closer to getting the job you always wanted.

If you like this article, then please share with your friends and colleagues, and don’t forget to follow javinpaul on Twitter!

64 comments :

Anonymous said...

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.

Javin @ spring interview questions answers said...

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.

Thanks
Javin

Anonymous said...

I was asked:
How would you implement a queue using two stacks?
How would you implement a Singleton in c++? (never heard of it before, so challenging)

Javin @ String split Java example said...

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.

Prabakar said...

Nice questions you can include the following

Write program to

Reverse a string without using array.reverse method

Write program to Reverse an integer

Write program to Print odd numbers from 1 to 100 to a text file.

Anonymous said...

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
thank you

Anonymous said...

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.

Anonymous said...

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.

Javin @ collection interview question said...

@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.

Anonymous said...

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

Anonymous said...

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.

programmer said...

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.

It also has some fantastic questions on programming like:

1) How do you find permutation and combination of given String?
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.

Mike said...

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.

Jason said...

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.

Anonymous said...

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......

Javin @ Java design pattern questions said...

@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.

Michael said...

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

Tim said...

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

Anonymous said...

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.

Anonymous said...

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.

Anonymous said...

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)

public static void findMissedValue(int a[],int totalnumber) {
int b[]=new int[totalnumber];

for(int i=0;i<a.length;i++) {
int v = a[i];
b[v] = 1;
}
for (int j=0;j<totalnumber;j++) {
if (b[j]==0) {
System.out.print(" "+j);
}
}
}

Anonymous said...

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.

if Interviewer requests not to use java structure such as HashSet or Hashtable , I have another solution using pure array operation
* 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
* second[]
Complexity is O(n+m)

public static int[] Find1stArrayIn2rdArray(int first[] , int second[]) {
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++) {

third[second[i]] = 1;
}
int k=0;
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];
return finalResult;
}

Anonymous said...

> 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?

Why the questions marks? Those aren't questions.

Unknown said...

Hi Javin,

For question 3, I was able to write a program that can do it using recursion, its here http://www.journaldev.com/526/java-program-to-find-all-permutations-of-a-string

But I was not able to write a program using iteration, do you have a solution for that?

For question 4, I wrote a program that you might want to check at http://www.journaldev.com/530/java-program-to-find-out-longest-palindrome-in-a-string

Hoping to get some inputs from your side.

Jacques Liao said...

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.

1. Sort two arrays independently ( O(n*log(n) time).
2. Marching two sorted array to find those duplicate numbers.

sohail said...

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.

Unknown said...

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.

int[] a = { 1, 2, 3, 4, 5, 8 };
int[] b = { 2, 3, 1, 0, 5 };

boolean isPresent = false;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
if (a[i] == b[j]) {
isPresent = true;
}
}
if (!isPresent) {
System.out.println("Not Present" + a[i]);
} else {
isPresent = false;
}
}
}

Anonymous said...

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

Anonymous said...

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

Gurpeet said...

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.

Anonymous said...

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':

Integer[] a = new Integer[]{1,2,3,4,5};
Integer[] b = new Integer[]{2,3,1,0,5};
Set setA = new HashSet<>(Arrays.asList(a));
Set setB = new HashSet<>(Arrays.asList(b));
setB.removeAll(setA);

System.out.println("Item(s) in B that are NOT in A are: "+setB);

Unknown said...

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

Unknown said...

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?

Anonymous said...

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

Anonymous said...

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).

Anonymous said...

can you give me the code for
Q)Biggest polidrome in a given string?

Anonymous said...

can you add some programming interview questions on multithreading concept?

Anonymous said...

Here's one I got:

Given a chessboard one Knight, determine whether there is a path through the chessboard, starting on any square, which would result in the Knight visiting every square on the board.

Unknown said...

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

Unknown said...

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?

Unknown said...

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.

I had just completed intro to java and I don't know anything about hashtables, so I simply created a nested for loop with an IF statement inside to compare every number 1 by 1. This will output a number from the first array that didn't match with the second array. Due to the nature of the loop, my output showed 4 five times, and so I added a break; to cut the loop. Is there an easier way to write my IF statement?
int x,y,nrows; int [] A= {1,2,3,4,5}; int [] B= {3,2,5,1,0}; nrows=5;
for(x=0; x<nrows; x++) { for(y=0; y<nrows; y++) { if(A[x]!=B[0]&&A[x]!=B[1]&&A[x]!=B[2]&&A[x]!=B[3]&&A[x]!=B[4]) System.out.println(A[x]); break; }
}
} //end class

Unknown said...

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

Ankita Pandit said...

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

Anonymous said...

@Ramesh Kumar
String newString = "";
String a = "My name is X Y Z";
int n = a.length();
int k = n-1;
int j=0;

for (int i=n-1; i>=0; i--)
{
if (a.charAt(i) == ' ' || i==0)
{

j= (i!=0)?i+1:i;

while(j<=k)
{
newString = newString + a.charAt(j);
j=j+1;
}
newString = newString + " ";
k=i-1;
}

}
System.out.println(newString);

Scott said...

@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.

Unknown said...

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?

I don't believe that any employer will ever expect from you to solve a problem without using frameworks API, that's just silly.
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.

Anonymous said...

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

Unknown said...

can you help me for writing this program
1234321
12321
121
1

Anonymous said...

//In an array 1-100 numbers are stored, one number is missing how do you find it?
$a=array(1,2,3,4,5,6,7,9,10);

for($x=0;$x<8;$x++)
{
$c1=$a[$x];
$c2=$a[$x+1];
if($c2==$c1+1)
{
$c1=$c1+1;
$c2=$c2+1;

}
else
{
echo $c1+1;
die();
}

}

CHANDRAYAAN 2 LANDING LIVE said...

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.

lucy said...

Hi,

The following two questions were asked for some of our students for a programming test:

1. Write a program to calculate the angle between the hour hand and the minute hand of a clock if the time is given in a string format. For example if the time is given as 12:15 the output should be 90degrees.
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.

Hope this helps someone.

Unknown said...

InterView Programming Problems topic wise
http://www.binarycoder.org/484-2/

likhin nelliyota said...

//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
///
//

#include "stdafx.h"
#include
#include
int main()
{
using namespace std;
int x1,x2,y1,y2,r1,r2;
cout<<"Enter center of big circle"<>x1>>y1;
cout<<"Enter Radius of big circle"<>r1;
cout<<"Enter center of Small circle"<>x2>>y2;
cout<<"Enter Radius of small circle"<>r2;

int distance=sqrt(pow((x1-x2),2)+pow((y1-y2),2));//To find distance between centers
if((r1-r2)>(distance))// circle is inside if distance is lessthan difference between radius
{
cout<<"YES"<<endl;
}
else
{
cout<<"NO"<<endl;
}
return 0;
}

Unknown said...

How to print this patter:-
A
BC
CDE
DEFG

10 Simple way anyone can impress a girl said...

Int[] input={121,122,123,124,126,127};
Output: 123,124,125,126,127
Removing repeated number 121 and 122.
Since 121 has two 1's llly 122 has two 2's. Any one suggest me

Unknown said...

matrix program accept matrix size by user
matrix size 3
output
1 5 7
4 2 9
6 8 3


Unknown said...

solution of;
1234321
12321
121
1

for(int a=4;a>=1;a--)
{
int v=1;
Console.WriteLine();
while(v<=a)
{
Console.Write(v);
v++;
}

v=v-2;
while (v >0)
{

Console.Write(v);
v--;

}

Unknown said...

Thanks for sharing this list of interview questions.

Anonymous said...

Just amazing. It covers almost all the major questions.

Anonymous said...

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

class Launch
{
public static void main(String[] args) {

String str = "forgeeksskeegfor";
System.out.println("Length is: " +
longestPalindrome(str));
}
public static String longestPalindrome(String s)
{
if(s==null || s.length()<=1)
return s;

int len = s.length();
int maxLen = 1;
boolean [][] dp = new boolean[len][len];

String longest = null;
for(int l=0; lmaxLen){
maxLen = j-i+1;
longest = s.substring(i, j+1);
}
}
}
}

return longest;
}


}

Anonymous said...

I think its more important for a candidate to know how to design an application correctly rather than to solve a math problem. In real world you almost never interact with these things. Think about what real problems are out their, legacy code, bad design, bugs. How would you tackle those, these these skills not math exercises like above. They are not solved by the above, but by quality design that can be surrounded by automated testing. A candidate can easily go to this page and learn all the solutions within 1 hour, but designing a class properly comes only with experience - and that is a real world problem found everywhere.

Unknown said...

For Question number 12 in array section :

public static void main(String[] args) {
Integer[] arrayOne = {1,2,3,4,5};
Integer[] arrayTwo = {2,3,1,0,5};


List listOne = new ArrayList(Arrays.asList(arrayOne));
List listTwo = new ArrayList(Arrays.asList(arrayTwo));

listOne.removeAll(listTwo);
for (Integer integer : listTwo) {
System.out.println(integer);
}

Muhammad Maaz said...

I was ask to write a random function of your own (a function which would take min and max value and give an output as a random number)(no library are allowed)

Unknown said...

Q4 : Food Delivery Booking
A food delivery company has 'n' number of delivery executives. For simplicity take the
count as 5 but the program should work for any number of delivery executives (Let their names
be identified as DE1, DE2....DE-n)
There are only 5 restaurants in the city for pick-up and 5 drop locations (Each location can have
multiple customers). After delivering a food package , the delivery executive waits there for
delivery allotment.
Each customer is identified uniquely by a Customer-ID.
Write a program that does the following,
Constraints :
1. Delivery charge for every single order is Rs 50 for the delivery executive.
2. If multiple orders (say n) are from the same delivery location within 15 mins period,
combine orders to a maximum of 5 per delivery executive. In such case, the delivery charge will
be base rate Rs.50 + Rs.5 for every other order (50+5 * (n-1)).
3. An allowance of Rs.10 will be given for every trip made. Combined orders will be
counted as a single trip.
4. Assign the subsequent bookings giving preference to the executive who has earned
the least delivery charge among the other available delivery executives excluding trip allowance.
5. Every trip will take 30 mins to reach the destination.
Questions :
1. Write a function to handle booking.
2. Write a function to assign delivery executive
3. Write a function that can display delivery executive's activity thus far. (This should
contain commission earned , allowance earned(calculated based on criteria 2 and 3).
Input 1
Customer ID: 1
Restaurant: A
Destination Point : D
Time : 9.00 AM
Output
Booking ID : 1
Available Executives :
Executive Delivery Charge Earned
DE1 0
DE2 0
DE3 0
DE4 0
DE5 0
Allotted Delivery Executive: DE1
-------------------------------------------------------------------------------------------------------------------
Input 2
Customer ID: 2
Restaurant : B
Destination Point : A
Time : 10.00 AM
Output
Booking ID : 2
Available Executives :
Executive Delivery Charge Earned
DE1 50
DE2 0
DE3 0
DE4 0
DE5 0
Allotted Delivery Executive: DE2
-------------------------------------------------------------------------------------------------------------------
Input 3
Customer ID: 3
Restaurant : B
Destination Point : A
Time : 10.10 AM
Output
Booking ID : 3
Available Executives :
Executive Delivery Charge Earned
DE1 50
DE2 50
DE3 0
DE4 0
DE5 0
Allotted Delivery Executive: DE2 (because same location within 15mins)
-------------------------------------------------------------------------------------------------------------------
Input 4
Customer ID: 3
Restaurant : D
Destination Point : C
Time : 10.35 AM
Output
Booking ID : 3
Available Executives :
Executive Delivery Charge Earned
DE1 50
DE2 55
DE3 0
DE4 0
DE5 0
Allotted Delivery Executive: DE3
-------------------------------------------------------------------------------------------------------------------
Delivery History
Output
TRIP EXECUTIVE RESTAURANT DESTINATION POINT ORDERS PICK-UP_TIME
DELIVERY_TIME DELIVERY CHARGE
1 DE1 A D 1 9:15
9:45 50
2 DE2 B A 2 10:15
10:45 55
3 DE3 D C 1 10:50
11:20 50
Total earned
Executive Allowance Deliver Charges Total
DE1 10 50 60
DE2 10 55 65
DE3 10 50 60

Post a Comment