71 Amazon Interview Questions With Answers You Must Know!
What characteristics do I look for when hiring somebody? That's one of the questions I ask when interviewing. I want to know what kind of they would hire.
-Jeff Bezos
This statement by Amazon CEO Jeff Bezos is a peek into the hiring methodology at the e-commerce giant. Getting the opportunity of interviewing at this organization is the stuff of dreams for many. So when you do get this opportunity, you want to give your best. And to help you in this endeavor, in this article we have listed some of the most important Amazon interview questions. We will also give you a brief on the Amazon interview process and rounds, along with some essential tips to smooth this journey out. So let's get started.
Amazon Recruitment Process
The Amazon recruitment process is split into 4 stages, as depicted in the image below.
In this article, we will focus on helping you prep for the interview rounds by listing top Amazon interview questions with answers. For more details on the Amazon recruitment process, check this article out- Everything About The Amazon Recruitment Process | Salary | Preparation Tips
Amazon Interview Rounds
The interview process will be made up of more than one round including a phone interview and multiple in-person interviews. The Amazon Behavioural Interview, Amazon Technical Interview, HR interview, etc are a few types of interviews you might have to go through. The type of Amazon interview questions asked during these rounds will depend on the kind of profile you are applying for. But irrespective, you must be prepared for anything that might come your way. There are four primary categories in which we can categorize most Amazon interview questions. They are:
Leadership principles | Behavioral interview questions |
Technical/ coding questions | Company-specific questions |
Job seekers appearing for software development engineering and similar profiles will be asked varied technical questions to test their suitability for the position, along with other types of questions. We have included a category-wise list of common interview questions in this article to help you prepare for the upcoming interview.
Common Amazon Interview Questions
In this section, we will see some of the most important, non-technical, Amazon interview questions for both freshers as well as experienced professionals. Most of these questions have subjective answers, but we have included sample answers with proper explanations everywhere.
Q1. Why do you want to join Amazon?
This is one of the most commonly asked Amazon interview questions. The intent behind this is to ascertain your motivation for wanting to become a part of the organization, and further ascertain if your motivations/ reasons align with the company's thought process and goals. Your answer should showcase your passion and enthusiasm to work at the multinational company.
Also, read- 6 Key Tips To Answer "Why Do You Want To Join Our Company?"
Sample answer:
I feel really inspired by the company's commitment to innovation and its ability to continually improve customer experience by introducing new products/ services. And also the ability to integrate cutting-edge technology to serve its purpose. I am also aware of the numerous growth opportunities that the company will provide me with and am super excited to take on this journey.
Q2. Tell me about yourself. Or What are your future goals?
How you answer this question is again completely subjective. The ideal way to answer such a question is to pick a quality or trait or incident from your present life (or current role), then segue into the past (or previous roles) by mentioning how that incident/ trait was functional in a certain aspect of your life. And then go on to derive an inference of how this will help you in your future professional and personal life.
For more details read- "Tell Me About Yourself" Here's How To Answer This Interview Question Like A Pro!
Q3. What makes you a good fit for this company? Or Why should we hire you?
The answer to this Amazon interview question can be the perfect opportunity for you to showcase how you are different from other candidates and convince the interviewer to hire you. To frame the perfect answer, read through the job description and use the requirements in there to prove your job fit, traits, skills, experience, etc.
For some sample answers read- How To Answer "Why Should We Hire You?" (With Examples)
Q4. In your previous company, which project was your favorite?
Take any past project or case that best portrays your skills and back it up with a proper explanation. If you are a fresher, you can use instances from your internship experiences to frame an answer.
Sample answer:
The development of a food delivery application was my favorite project as we got to learn many new aspects of software development.
Q5. Have there been conflicts with a superior/ manager?
The interviewer's intent behind asking this question is most probably to see how you handle conflicting situations. It is best, to be honest, and clearly state an instance of conflict you have faced.
Sample answer for tech roles is:
Normally tech companies are always extremely sorted. There have been times when I had a difference of opinion with my manager, but never an issue of conflict because of effective communication from both sides.
Q6. Did any of your ideas get implemented and resolve the issue?
With this answer, the interviewer is most probably trying to see if you are proactive, take initiative, and have analytical skills & out-of-the-box thinking. Try to showcase that you do possess these traits with the help of a past incident and give a proper explanation.
Sample answer:
I have used the shuffling method in the core development team where developers switch roles after a fixed time period to relieve them of work pressure. This idea got implemented and resolved the issues of our company's IT team and also the non-IT team.
Q7. Any example of you working out of your comfort zone?
Adaptability and agility are extremely important traits for those who want to thrive in the corporate world today. And the intent of this Amazon interview question is to see if you do too. So frame an answer that showcases this, and assures the interviewer that you are the ideal candidate for the job.
Sample Answer:
Every project has its challenging bits which require us to work out of our comfort zone. I cannot singularly point to such instances as there are many of them.
Q8. The most critical/ negative feedback you got from your team or manager.
Senior people give correct insights most of the time. But I won't call them critical as they were concerned for my well-being. I have worked overtime multi-tasking and my health has suffered as a result. The manager asked me to not strain much over an issue. Apart from this, I have never received any critical feedback.
Q9. Any time when you were faced with a problem that had a number of possible solutions. What problem you faced and how did you solve it? What was the result you got after employing that solution?
This is an important Amazon interview question for freshers as well as professionals. This is because there are many times in our lives we come to a crossroads, and the way we proceed then says a lot about our being. Have a look at the sample answer below to know how to answer this question.
Sample answer:
There was an instance in midst of a project where the testing part could be done in multiple ways. But, we took the simplest test and the result of it was that we could find all the flaws in the code in a single step and we didn't have to revise the code multiple times.
Q10. When did you take a risk, failed, or made a mistake? How do you respond to difficult situations and what was the experience you gained out of them?
Although, there have been some instances when I have made a mistake after taking a risk. But such instances have been very few. There is no exceptional mistake that I have made till this point in my career. But if you want a single instance. During one project where we had limited time for the development of software, I used a particular tried and tested method to get the project delivered before the deadline. However, due to some reason, we lagged and delivered the project two days after the deadline. That is the only time I took a risk and failed to deliver. But I kept my focus and kept on going along with the team and did not take much time to deliver the project even after the given deadline.
Q11. Describe an instance when you led a project.
As you will see in the article ahead, leadership skills and principles are especially important for Amazon. Answering this Amazon interview question right is your shot of grabbing brownie points.
Sample answer:
Yes, during one project where we had to develop banking software for a team, I led my team and received positive feedback mostly from my peers, my team, and my seniors. My leadership role was appreciated and I was made a team lead after that project.
Q12. Have you used data and developed a strategy?
Yes, I have done so in my previous company/internship. I had to wrangle a large data set to create a strategy for building a food delivery application. The development of the app was data-driven, so we had to be careful with the deployment of the app at every step. We made a strategy and managed to develop the food delivery app at the optimum time. (This is a sample answer to these types of questions. You can use your storytelling ability to concisely tell the recruiters about your capability to deal with a difficult decision in your previous job experience. The answer should bear a positive impact on the interview.)
This brings us to the end of the common Amazon interview questions segment. From here we will move on to one of the most important segments for job profiles across departments at Amazon. That is, behavioral questions since they are integral to determining if a candidate is suitable for the company and its work culture, or not.
Amazon Interview Questions: Behavioral-based Questions
The behavioral-based questions asked in Amazon interviews are intent on finding out about the past situations and challenges, candidates have come across. And also the way they have handled these situations. The foundation of these behavioral-based interview questions lies in the 16 Leadership Principles stated by Amazon.
You can use these very Amazon core leadership principles to frame your responses in a way that shows you have all the qualities they are looking for. We have specified the principles in the section ahead. We will also discuss, one of the best ways to prepare for these behavioral questions before having a look at some common Amazon interview questions in this category.
Preparing for Amazon Behavioral Questions
The best way to prepare for behavioral interview questions asked at Amazon is the STAR method. This stands for:
- Situation: Quickly describe the situation. It’s best to focus on a specific moment, like an event or a team project.
- Task: Explain the goal you have labored for. This is a point where you faced an obstacle.
- Action: Describe how you and your team tackled the problem describing the process step by step.
- Result: What was the result of your team's endeavors? For this question, specificity is your best friend.
Use specific examples with specific numbers, wherever possible. The S-T-A-R method is a winning strategy when tackling such behavioral interview questions. Ensure each answer has a beginning, middle, and end. Describe the situation or problem, the actions you took, and the outcome.
Q13. Share an instance where you found an innovative solution to a problem.
The intent behind this question is to assess your innovative ability and also the ability o convert that into actionable plans. Take any instance from the past, and explain the situation along with the steps you took to materialize the solutions. Also mention how that benefited you as well as the organization you were a part of.
Q14. What are your strengths and weakness?
If you are thinking that sharing your weaknesses is a bad idea, it is not. In contrast, mentioning your weaknesses and strengths and explaining how you are working on them shows self-awareness. It also iterates on the fact that you are willing to work on your issues and wish to grow. So be honest and frame a proper answer to this Amazon interview question. Make sure to leave an impression on the interviewer.
Read these articles to find the perfect answer- What Is Your Greatest Weakness? Here's The Perfect Reply and Guide To Answer- "What Is Your Greatest Strength?" (Samples Inside)
Q15. Say your team members are not pulling their weight. How would you handle that?
This is not an uncommon occurrence in workplaces, and the way you handle such situations will tell the interviewer a lot about your capabilities and personality. Ignoring this situation and continuing your work will make you look ignorant. Some might think telling on your colleague is the way to go, but it shows untrustworthiness and incapability in solving problems. Your answer to this Amazon interview question must highlight your positives while showing that you have the ability to take tough decisions.
Sample answer:
The best way to handle these situations is to first have an intra-team discussion and make it clear that such behavior won’t work. Discussing it within your team shows that you are a team player, and bringing these issues up positively but sternly shows that you can stand up for yourself and the company’s interests. Also discussing the problem shows support towards teammates and willingness to find out, as well as work on the root cause of the problem.
Q16. Was there ever a time when you had to pivot completely before the completion of a project? How did you take it?
The corporate world today is changing at an extremely fast pace. And those who want to keep up must know how to pivot quickly. Your answer must show that you are prepared to change with time and work towards your goals undeterred.
Sample answer:
One of the projects I was working on in my previous job was near completion everything was proceeding in a timely fashion. But at the last moment, we encountered a system breach and we were thrown off balance. We had two options, one to take the loss and delay of about 3-4 weeks. And the second was to reallocate our resources to adopt a new approach that would help us recover from the breach in half the time. I initiated the reallocation and the pivot ultimately helped us stay ahead in the game.
Q17. Can you tell an instance of how you motivated your team during a particular project?
Yes, there was a time when we were building a difficult piece of software for a client company and the development time was extremely long. I suggested a switch role method for the core development team and it worked effectively because every developer got a chance to shuffle their role and get revived from mental stagnancy. After that, the entire company started using this method for various teams.
Q18. What according to you is more important- money or work?
Another tricky Amazon interview question, that might come your way during the interview. The answer to this is completely subjective, a sample answer is given below.
Sample Answer:
I believe both money and work are important, if you work hard enough, then money will follow. And money acts as one of the motivating factors that pushed one to work hard. So it is not an either-or situation, instead one of these fuels the other, and vice versa.
Amazon Interview Questions: Leadership Principles
Amazon takes its leadership principles extremely seriously and they hold relevance in all aspects of the organization, be it hiring, brainstorming, or decision-making. It is not surprising then that Amazon interview questions will also be based on these. The principles are:
Customer Obsession (Leaders work vigorously to earn and keep customer trust. And while they do pay attention to competitors, they are obsessed with customers.) |
Ownership (Leaders are owners who think about the bigger picture i.e. they don't sacrifice long-term value for short-term benefits. You will never hear them saying- 'that's' not my job'.) |
Invent and Simplify (Leaders always, always look for new ideas everywhere and require/ expect the same from their teams.) |
Think Big |
Learn and Be Curious (Leaders are always curious about new things and never stop learning.) |
Hire and Develop the Best |
Frugality (Leaders know how to accomplish more with less.) |
|
Insist on the Highest Standards |
Earn Trust |
Bias for Action (Leaders know when to put extensive study aside and take quick action on calculated risks since speed is important in business.) |
Deliver Results (Leaders rise to the occasion despite setbacks and always deliver results with the right quality and in a timely fashion.) |
Are right, A Lot (Leaders are right a lot. They have strong judgment and good instincts. They seek diverse perspectives and work to disconfirm their beliefs.) |
Dive Deep (No task is beneath the leaders. They operate at all levels and stay connected to the details) |
Have Backbone; Disagree and Commit (Leaders are obligated to act with conviction, and respectfully challenge decisions when needed. And once a decision is determined, they commit wholly.) |
Strive to be Earth's Best Employer (Leaders lead with empathy to work every day to create a safer, more productive, higher performing, more diverse, and just work environment while also making it easy for all to have fun at work.) |
Success and Scale Bring Broad Responsibility (We have come a long way from a garage. And with the greater impact we have on the world, we have to be humble and thoughtful about even the secondary effects of our actions. We must begin each day with a determination to make better, do better, and be better for our customers, our employees, our partners, and the world at large.) |
The principles also form the foundation of many behavioral questions. Now let's have a look at a few leadership principles based Amazon interview questions and sample answers.
Q19. What was the biggest mistake of your life? And how did you overcome it?
The best way to answer this Amazon interview question is to take an experience from your life and explain it in detail but with the context of how it helped you grow. It is important to show that you learned from that mistake and have grown into a refined version.
Q20. Are you short-tempered? What angers you the most?
Being angry isn't a bad thing till the time you know how to control it, and channel it right. So take any instance where you were agitated and reflect on how to found a solution to the anger issues, or how you channeled it and made something good out of it, etc.
Q21. What would you do if one of your colleagues stole an item worth $1?
It should be clear to you that the small amount of theft is a trap. While normal human behavior is to think that this is such a small amount that it won't affect the company's bottom line. But think what will happen if everyone stole $1 and turned a blind eye to others doing the same. Also, note that shrinkage is a major concern for Amazon. So there is only one right answer to this Amazin interview question.
Sample Answer:
Irrespective of the amount, theft is theft and must be addressed since it's not only against policy but also illegal. So if I witnessed something like this, I would follow company procedure and report it.
Q22. What is the way to understand customer needs?
Amazon places great importance on 'customer obsession' and aims to provide the best customer service. And to do so you need to know how to understand customer needs and must show the same to the interviewer.
Sample Answer:
I believe active/ keen listening skills, observational and analytical skills, and asking questions to get more insights, are key to understanding customer needs. And this is critical to ensuring customer satisfaction.
Q23. What is frugality and how do you commit to it in the workplace?
Note that 'frugality' is one of the core Amazon leadership principles. So you might come across this Amazon interview question. Your answer to this question must showcase that you know how to manage and save time, money, and other resources while delivering quality results.
Sample answer:
I believe that being frugal and inculcating it in your work methodology is important. In my previous role, I discovered an alternate software for one of our functions. This software did not only cost less comparatively but improved efficiency with enhanced features. I took this to my manager and we switched to it after a demo.
There are sixteen leadership principles in total with a wide scope of applicability. It is important that you understand these principles because a lot of Amazon interview questions can be based on them. One way to prepare is to analyze instances when Amazon applied these principles. For example, there are many instances where they showed exceptional customer obsession and went out of the way to gain customer trust. Try to incorporate them in your answers to such Amazon interview questions.
Company-specific Amazon Interview Questions
Amazon is a popular and widely known e-commerce giant, but you still need to prepare for company-specific Amazon interview questions you might come across. Some are:
Q24. Who is our CEO? How to spell and pronounce his name?
Jeff Bezos [pronunciation- Jef bay-zohs]
Q25. What do you understand by our 'Strive to be Earth's best employer' principle?
To answer this Amazon interview question, explain your understanding of this principle while also connecting with your own personality and how you would emulate it in work life.
Q26. What do you think is one of the biggest challenges for Amazon, today?
It is obvious that before interviewing at the company you do your homework and conduct a deep analysis of the organization. Use that knowledge to highlight what you think is a challenge and also how you would solve it.
Q27. Give me an elevator pitch for Amazon.
We all know that the purpose of an elevator pitch is to give a quick intro while putting two-three important points across, in a duration equivalent to taking an elevator ride. A sample answer to this Amazon interview question is given below.
Sample pitch:
From a modest garage startup to becoming a multinational e-commerce/ technology giant, Amazon is the brainchild of Jeff Bezos. It truly lives up to its namesake, the Amazon river as it spans the e-commerce, online advertising, cloud computing, digital streaming, and artificial intelligence sectors.
Q28. Which Amazon leadership principles do you relate to the most, and why?
There are 16 principles in total, read through all of them and reflect on the ones you relate to the most. Irrespective of whether the interviewer asks you this Amazon interview question or not, you must have a deep understanding of these principles if you want to work at the company.
43 Top Technical/ Coding Amazon Interview Questions
Amazon operations are largely dependent upon technology, which is why the giant hires skilled professionals for numerous technical roles like software developers, etc. Naturally, the Amazon interview questions for such profiles will consist of coding/ tech questions. There are four blocks of interview rounds for tech profiles specifically software development engineer (SDE). These are classified on the basis of interviewers i.e. hiring manager, bar raiser, interviewers, and shadows. It is important to note that each of these interviewers will test you on both leadership competencies as well as technical competencies.
We have already elaborated on the leadership and behavioral questions. In this section, we will have a look at some common Amazon interview questions and answers that test tech competencies.
Q1. Give examples of greedy algorithms.
Graph - Map Coloring | Graph - Vertex Cover |
Kruskal's Minimal Spanning Tree Algorithm | Prim's Minimal Spanning Tree Algorithm |
Travelling Salesman Problem | Knapsack Problem |
Job Scheduling Problem | Dijkstra's Minimal Spanning Tree Algorithm |
Q2. Define checked exception.
A checked exception also referred to as a compile-time exception, is a fault in the code that can be recovered, as against unchecked exceptions, something wrong in the code that cannot be recovered.
Q3. What is a data structure and its types?
A data structure refers to the relationship between the multiple data and the technique to manage, organize, and efficiently sort said data. There are two types- linear and non-linear data structure. Linear data structures are ones that store data linearly or sequentially. Some examples are queues, stacks, arrays, etc. Non-linear data structures are more complex structures that are connected to the multiple, previous, and next elements. Its examples are tree, graph, and hashmap.
Q4. Explain operator overloading.
Also referred to as operator ad hoc polymorphism, operator overloading is when different operators have different implementations in reference to the arguments.
Q5. What does tree traversal mean?
Tree traversal refers to the process of visiting each tree node in the data structure, just once. This can be done in three ways i.e. inorder, preorder, and postorder.
Q6. What is the meaning of a database?
The database is the term used to refer to a collection of organized data stored in a computer system that be accessed electronically.
The Amazon interview questions listed above were some of the most basic tech-related questions. Now let's have a look at some coding questions that will help you prepare for your interview.
Q7. How do you find the missing number in the array?
package com.devglan;
import java.util.Arrays;
public class FindMissingNumber {
public static int calculateSumOfNNumbers(int n){
return (n * (n + 1))/2;
}
public static int calculateSum(int [] array){
return Arrays.stream(array).sum();
}
public static void main(String [] args){
int n = 9;
int[] numbers = {1, 2, 4, 9, 7, 8, 5, 6};
int nNumberSum = FindMissingNumber.calculateSumOfNNumbers(n);
int sumOfArray = calculateSum(numbers);
int missingNumber = nNumberSum - sumOfArray;
System.out.println(String.format("The missing number is: %s", missingNumber));
}
}
Q8. Determine whether the sum of two integers is equal to the value that is given.
import java.util.*;
public class Exercise52 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input the first number : ");
int x = in.nextInt();
System.out.print("Input the second number: ");
int y = in.nextInt();
System.out.print("Input the third number : ");
int z = in.nextInt();
System.out.print("The result is: "+sumoftwo(x, y, z));
System.out.print("\n");
}
public static boolean sumoftwo(int p, int q, int r)
{
return ((p + q) == r || (q + r) == p || (r + p) == q);
}
}
Q9. Write how to merge two sorted linked lists.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
}
};
Q10. How to copy the linked list with an arbitrary pointer?
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
public Node copyRandomList(Node head) {
}
}
Q11. Level Order Traversal of Binary Tree.
/* Class containing left and right child of current
node and key value*/
class Node {
int data;
Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree {
// Root of the Binary Tree
Node root;
public BinaryTree() { root = null; }
/* function to print level order traversal of tree*/
void printLevelOrder()
{
int h = height(root);
int i;
for (i = 1; i <= h; i++)
printCurrentLevel(root, i);
}
/* Compute the "height" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(Node root)
{
if (root == null)
return 0;
else {
/* compute height of each subtree */
int lheight = height(root.left);
int rheight = height(root.right);
/* use the larger one */
if (lheight > rheight)
return (lheight + 1);
else
return (rheight + 1);
}
}
/* Print nodes at the current level */
void printCurrentLevel(Node root, int level)
{
if (root == null)
return;
if (level == 1)
System.out.print(root.data + " ");
else if (level > 1) {
printCurrentLevel(root.left, level - 1);
printCurrentLevel(root.right, level - 1);
}
}
/* Driver program to test above functions */
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
System.out.println("Level order traversal of
binary tree is ");
tree.printLevelOrder();
}
}
Q12. How would you determine whether the binary tree is a binary search tree or not?
boolean isBST(Node node)
{
if (node == null)
return true;
/* False if left is > than node */
if (node.left != null && node.left.data > node.data)
return false;
/* False if right is < than node */
if (node.right != null && node.right.data < node.data)
return false;
/* False if, recursively, the left or right is not a BST */
if (!isBST(node.left) || !isBST(node.right))
return false;
/* Passing all that, it's a BST */
return true;
}
Q13. Do string segmentation.
class Solution {
public boolean wordBreak(String s, List wordDict) {
}
}
Q14. How many ways can you make a change with coins and a total amount?
import java.util.*;
class GFG
{
// Returns the count of ways we can
// sum S[0...m-1] coins to get sum n
static int count(int S[], int m, int n)
{
// If n is 0 then there is 1 solution
// (do not include any coin)
if (n == 0)
return 1;
// If n is less than 0 then no
// solution exists
if (n < 0)
return 0;
// If there are no coins and n
// is greater than 0, then no
// solution exist
if (m <= 0)
return 0;
// count is sum of solutions (i)
// including S[m-1] (ii) excluding S[m-1]
return count(S, m - 1, n) +
count(S, m, n - S[m - 1]);
}
// Driver code
public static void main(String args[])
{
int arr[] = { 1, 2, 3 };
int m = arr.length;
System.out.println(count(arr, m, 4));
}
}
Q15. Find Kth permutation.
public class Solution {
private static final int[] FACT = { // 479001600 < 2147483647 < 6227020800
1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600
};
public List<List> permute(int[] nums) {
Arrays.sort(nums);
List<List> result = new ArrayList<>(nums.length);
for (int k = 0; k < FACT[nums.length]; ++k) {
result.add(permutation(nums, k));
}
return result;
}
List permutation(int[] nums, int k) {
// k %= FACT[nums.length]; // in case you want to use it elsewhere
List source = toList(nums);
List result = new ArrayList(nums.length);
while (!source.isEmpty()) {
int f = FACT[source.size() - 1];
result.add(source.remove(k / f));
k %= f;
}
return result;
}
List toList(int[] nums) {
List result = new LinkedList<>();
for (int num : nums) {
result.add(num);
}
return result;
}
}
When you are interviewing for an SDE or any other tech role, will be asked a variety of tech Amazon interview questions which will vary in terms of difficulty. The questions above were beginner level but you can expect the question to be a little more complex as rounds progress.
Another important thing to note here is that many candidates do not prepare well for behavioral questions and are too focused on tech ones. But since every interviewer in a block is allotted both principles and tech competencies, you must be well-versed in all segments. Now let's have a look at a few coding questions of intermediate difficulty level.
Q16. Write the code to find all of the subsets of a set of integers that is given.
import java.io.IOException;
class Main
{
// Print all subsets of given set[]
static void printSubsets(char set[])
{
int n = set.length;
// Run a loop for printing all 2^n
// subsets one by one
for (int i = 0; i < (1<<n); i++)
{
System.out.print("{ ");
// Print current subset
for (int j = 0; j < n; j++)
// (1<<j) is a number with jth bit 1
// so when we 'and' them with the
// subset number we get which numbers
// are present in the subset and which
// are not
if ((i & (1 << j)) > 0)
System.out.print(set[j] + " ");
System.out.println("}");
}
}
// Driver code
public static void main(String[] args)
{
char set[] = {'a', 'b', 'c'};
printSubsets(set);
}
}
Q17. How to print balanced brace combinations?
import java.io.IOException;
class Main
{
// Print all subsets of given set[]
static void printSubsets(char set[])
{
int n = set.length;
// Run a loop for printing all 2^n
// subsets one by one
for (int i = 0; i < (1<<n); i++)
{
System.out.print("{ ");
// Print current subset
for (int j = 0; j < n; j++)
// (1<<j) is a number with jth bit 1
// so when we 'and' them with the
// subset number we get which numbers
// are present in the subset and which
// are not
if ((i & (1 << j)) > 0)
System.out.print(set[j] + " ");
System.out.println("}");
}
}
// Driver code
public static void main(String[] args)
{
char set[] = {'a', 'b', 'c'};
printSubsets(set);
}
}
Q18. Give the code to clone a Directed Graph.
/*
// Definition for a Node.
class Node {
public int val;
public List neighbors;
public Node() {
val = 0;
neighbors = new ArrayList();
}
public Node(int _val) {
val = _val;
neighbors = new ArrayList();
}
public Node(int _val, ArrayList _neighbors) {
val = _val;
neighbors = _neighbors;
}
}
*/
class Solution {
public Node cloneGraph(Node node) {
}
}
Q19. How to find the Low/ High Index?
class Solution {
public int[] searchRange(int[] nums, int target) {
}
}
Q20. Write the code to search Rotated Array.
class Solution {
public int search(int[] nums, int target) {
}
}
Q21. What is the method to find the K largest elements from an array?
import java.util.Arrays;
import java.util.Collections;
import java.util.ArrayList;
class GFG {
public static void kLargest(Integer[] arr, int k)
{
// Sort the given array arr in reverse order
// This method doesn't work with primitive data
// types. So, instead of int, Integer type
// array will be used
Arrays.sort(arr, Collections.reverseOrder());
// Print the first kth largest elements
for (int i = 0; i < k; i++)
System.out.print(arr[i] + " ");
}
public static ArrayList kLargest(int[] arr, int k)
{
//Convert using stream
Integer[] obj_array = Arrays.stream( arr ).boxed().toArray( Integer[] :: new);
Arrays.sort(obj_array, Collections.reverseOrder());
ArrayList list = new ArrayList<>(k);
for (int i = 0; i < k; i++)
list.add(obj_array[i]);
return list;
}
public static void main(String[] args)
{
Integer arr[] = new Integer[] { 1, 23, 12, 9,
30, 2, 50 };
int k = 3;
kLargest(arr, k);
//This code is contributed by Niraj Dubey
//What if primitive datatype array is passed and wanted to return in ArrayList
int[] prim_array = { 1, 23, 12, 9, 30, 2, 50 };
System.out.print(kLargest(prim_array, k));
}
}
Q22. How would you convert a Binary tree to DLL?
// A Java program for in-place conversion of Binary Tree to DLL
// A binary tree node has data, left pointers and right pointers
class Node
{
int data;
Node left, right;
public Node(int data)
{
this.data = data;
left = right = null;
}
}
class BinaryTree
{
Node root;
// head --> Pointer to head node of created doubly linked list
Node head;
// Initialize previously visited node as NULL. This is
// static so that the same value is accessible in all recursive
// calls
static Node prev = null;
// A simple recursive function to convert a given Binary tree
// to Doubly Linked List
// root --> Root of Binary Tree
void BinaryTree2DoubleLinkedList(Node root)
{
// Base case
if (root == null)
return;
// Recursively convert left subtree
BinaryTree2DoubleLinkedList(root.left);
// Now convert this node
if (prev == null)
head = root;
else
{
root.left = prev;
prev.right = root;
}
prev = root;
// Finally convert right subtree
BinaryTree2DoubleLinkedList(root.right);
}
/* Function to print nodes in a given doubly linked list */
void printList(Node node)
{
while (node != null)
{
System.out.print(node.data + " ");
node = node.right;
}
}
// Driver program to test above functions
public static void main(String[] args)
{
// Let us create the tree as shown in above diagram
BinaryTree tree = new BinaryTree();
tree.root = new Node(10);
tree.root.left = new Node(12);
tree.root.right = new Node(15);
tree.root.left.left = new Node(25);
tree.root.left.right = new Node(30);
tree.root.right.left = new Node(36);
// convert to DLL
tree.BinaryTree2DoubleLinkedList(tree.root);
// Print the converted List
tree.printList(tree.head);
}
}
Q23. Given a binary tree T, find the maximum path sum. The path may begin and conclude at any of the tree's nodes.
class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = right = null;
}
}
// An object of Res is passed around so that the
// same value can be used by multiple recursive calls.
class Res {
public int val;
}
class BinaryTree {
// Root of the Binary Tree
Node root;
// This function returns overall maximum path sum in 'res'
// And returns max path sum going through root.
int findMaxUtil(Node node, Res res)
{
// Base Case
if (node == null)
return 0;
// l and r store maximum path sum going through left and
// right child of root respectively
int l = findMaxUtil(node.left, res);
int r = findMaxUtil(node.right, res);
// Max path for parent call of root. This path must
// include at-most one child of root
int max_single = Math.max(Math.max(l, r) + node.data,
node.data);
// Max Top represents the sum when the Node under
// consideration is the root of the maxsum path and no
// ancestors of root are there in max sum path
int max_top = Math.max(max_single, l + r + node.data);
// Store the Maximum Result.
res.val = Math.max(res.val, max_top);
return max_single;
}
int findMaxSum() {
return findMaxSum(root);
}
// Returns maximum path sum in tree with given root
int findMaxSum(Node node) {
// Initialize result
// int res2 = Integer.MIN_VALUE;
Res res = new Res();
res.val = Integer.MIN_VALUE;
// Compute and return result
findMaxUtil(node, res);
return res.val;
}
/* Driver program to test above functions */
public static void main(String args[]) {
BinaryTree tree = new BinaryTree();
tree.root = new Node(10);
tree.root.left = new Node(2);
tree.root.right = new Node(10);
tree.root.left.left = new Node(20);
tree.root.left.right = new Node(1);
tree.root.right.right = new Node(-25);
tree.root.right.right.left = new Node(3);
tree.root.right.right.right = new Node(4);
System.out.println("maximum path sum is : " +
tree.findMaxSum());
}
}
Q24. How to rotate a given matrix by 90 degrees?
import java.io.*;
class GFG {
// An Inplace function to
// rotate a N x N matrix
// by 90 degrees in
// anti-clockwise direction
static void rotateMatrix(int N, int mat[][])
{
// Consider all squares one by one
for (int x = 0; x < N / 2; x++) {
// Consider elements in group
// of 4 in current square
for (int y = x; y < N - x - 1; y++) {
// Store current cell in
// temp variable
int temp = mat[x][y];
// Move values from right to top
mat[x][y] = mat[y][N - 1 - x];
// Move values from bottom to right
mat[y][N - 1 - x]
= mat[N - 1 - x][N - 1 - y];
// Move values from left to bottom
mat[N - 1 - x][N - 1 - y]
= mat[N - 1 - y][x];
// Assign temp to left
mat[N - 1 - y][x] = temp;
}
}
}
// Function to print the matrix
static void displayMatrix(int N, int mat[][])
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
System.out.print(" " + mat[i][j]);
System.out.print("\n");
}
System.out.print("\n");
}
/* Driver program to test above functions */
public static void main(String[] args)
{
int N = 4;
// Test Case 1
int mat[][] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
// Test Case 2
/* int mat[][] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
*/
// Test Case 3
/*int mat[][] = {
{1, 2},
{4, 5}
};*/
// displayMatrix(mat);
rotateMatrix(N, mat);
// Print rotated matrix
displayMatrix(N, mat);
}
}
Q25. Create assembly line scheduling with dynamic programming.
import java.io.*;
class GFG
{
static int NUM_LINE = 2;
static int NUM_STATION = 4;
// Utility function to find minimum of two numbers
static int min(int a, int b)
{
return a < b ? a : b;
}
static int carAssembly(int a[][], int t[][], int e[], int x[])
{
int T1[]= new int [NUM_STATION];
int T2[] =new int[NUM_STATION] ;
int i;
// time taken to leave first station in line 1
T1[0] = e[0] + a[0][0];
// time taken to leave first station in line 2
T2[0] = e[1] + a[1][0];
// Fill tables T1[] and T2[] using
// the above given recursive relations
for (i = 1; i < NUM_STATION; ++i)
{
T1[i] = min(T1[i - 1] + a[0][i],
T2[i - 1] + t[1][i] + a[0][i]);
T2[i] = min(T2[i - 1] + a[1][i],
T1[i - 1] + t[0][i] + a[1][i]);
}
// Consider exit times and return minimum
return min(T1[NUM_STATION-1] + x[0],
T2[NUM_STATION-1] + x[1]);
}
// Driver code
public static void main (String[] args)
{
int a[][] = {{4, 5, 3, 2},
{2, 10, 1, 4}};
int t[][] = {{0, 7, 4, 5},
{0, 9, 2, 8}};
int e[] = {10, 12}, x[] = {18, 7};
System.out.println(carAssembly(a, t, e, x));
}
}
In the later rounds of the tech interview section, interviewers generally ask a single Amazon interview question that you must solve quickly, leaving them time for further discussion. Once the coding question is done, it is continued by a detailed discussion on previous work experience, internships, or projects and consists of just behavioral interview questions. The difficulty level of this Amazon interview question will be medium to high. Let's have a look at some such questions.
Q28. What is the code to sort an integer array or an array of characters?
import java.util.Arrays;
class GFG {
public static void main(String args[])
{
int[] arr = { 5, -2, 23, 7, 87, -42, 509 };
System.out.println("The original array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
Arrays.sort(arr);
System.out.println("\nThe sorted array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
Q29. How do you rotate an input array by K?
import java.util.*;
import java.lang.*;
import java.io.*;
class Array_Rotation
{
// Function to rightRotate array
static void RightRotate(int a[],
int n, int k)
{
// If rotation is greater
// than size of array
k=k%n;
for(int i = 0; i < n; i++)
{
if(i<k)
{
// Printing rightmost
// kth elements
System.out.print(a[n + i - k]
+ " ");
}
else
{
// Prints array after
// 'k' elements
System.out.print(a[i - k]
+ " ");
}
}
System.out.println();
}
// Driver program
public static void main(String args[])
{
int Array[] = {1, 2, 3, 4, 5};
int N = Array.length;
int K = 2;
RightRotate(Array, N, K);
}
}
Q30. Design a Game of snakes using OOPS analysis and design techniques.
public class Cell {
private final int row, col;
private CellType cellType;
public Cell(int row, int col)
{
this.row = row;
this.col = col;
}
public CellType getCellType()
{
return cellType;
}
public void setCellType(CellType cellType)
{
this.cellType = cellType;
}
public int getRow()
{
return row;
}
public int getCol()
{
return col;
}
}
Q31. Write the code to print all permutations of a string that is given using recursion.
#include <bits/stdc++.h>
using namespace std;
// Function to print permutations of string
// This function takes three parameters:
// 1. String
// 2. Starting index of the string
// 3. Ending index of the string.
void permute(string a, int l, int r)
{
// Base case
if (l == r)
cout<<a<<endl;
else
{
// Permutations made
for (int i = l; i <= r; i++)
{
// Swapping done
swap(a[l], a[i]);
// Recursion called
permute(a, l+1, r);
//backtrack
swap(a[l], a[i]);
}
}
}
// Driver Code
int main()
{
string str = "ABC";
int n = str.size();
permute(str, 0, n-1);
return 0;
}
Q32. How do you implement a queue using a linked list?
class QNode {
int key;
QNode next;
// constructor to create a new linked list node
public QNode(int key)
{
this.key = key;
this.next = null;
}
}
// A class to represent a queue
// The queue, front stores the front node of LL and rear stores the
// last node of LL
class Queue {
QNode front, rear;
public Queue()
{
this.front = this.rear = null;
}
// Method to add an key to the queue.
void enqueue(int key)
{
// Create a new LL node
QNode temp = new QNode(key);
// If queue is empty, then new node is front and rear both
if (this.rear == null) {
this.front = this.rear = temp;
return;
}
// Add the new node at the end of queue and change rear
this.rear.next = temp;
this.rear = temp;
}
// Method to remove an key from queue.
void dequeue()
{
// If queue is empty, return NULL.
if (this.front == null)
return;
// Store previous front and move front one node ahead
QNode temp = this.front;
this.front = this.front.next;
// If front becomes NULL, then change rear also as NULL
if (this.front == null)
this.rear = null;
}
}
// Driver class
public class Test {
public static void main(String[] args)
{
Queue q = new Queue();
q.enqueue(10);
q.enqueue(20);
q.dequeue();
q.dequeue();
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
q.dequeue();
System.out.println("Queue Front : " + q.front.key);
System.out.println("Queue Rear : " + q.rear.key);
}
}
Q33. Find the longest ascending sub-sequence of an array.
class LIS {
static int max_ref; // stores the LIS
/* To make use of recursive calls, this function must
return two things: 1) Length of LIS ending with element
arr[n-1]. We use max_ending_here for this purpose 2)
Overall maximum as the LIS may end with an element
before arr[n-1] max_ref is used this purpose.
The value of LIS of full array of size n is stored in
*max_ref which is our final result */
static int _lis(int arr[], int n)
{
// base case
if (n == 1)
return 1;
// 'max_ending_here' is length of LIS ending with
// arr[n-1]
int res, max_ending_here = 1;
/* Recursively get all LIS ending with arr[0],
arr[1] ... arr[n-2]. If arr[i-1] is smaller
than arr[n-1], and max ending with arr[n-1] needs
to be updated, then update it */
for (int i = 1; i < n; i++) {
res = _lis(arr, i);
if (arr[i - 1] < arr[n - 1]
&& res + 1 > max_ending_here)
max_ending_here = res + 1;
}
// Compare max_ending_here with the overall max. And
// update the overall max if needed
if (max_ref < max_ending_here)
max_ref = max_ending_here;
// Return length of LIS ending with arr[n-1]
return max_ending_here;
}
// The wrapper function for _lis()
static int lis(int arr[], int n)
{
// The max variable holds the result
max_ref = 1;
// The function _lis() stores its result in max
_lis(arr, n);
// returns max
return max_ref;
}
// driver program to test above functions
public static void main(String args[])
{
int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
int n = arr.length;
System.out.println("Length of lis is " + lis(arr, n)
+ "\n");
}
}
Q34. Find the lowest common ancestor in a Binary Search Tree and Binary Tree.
class Node
{
int data;
Node left, right;
Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree
{
Node root;
/* Function to find LCA of n1 and n2. The function assumes that both
n1 and n2 are present in BST */
Node lca(Node node, int n1, int n2)
{
if (node == null)
return null;
// If both n1 and n2 are smaller than root, then LCA lies in left
if (node.data > n1 && node.data > n2)
return lca(node.left, n1, n2);
// If both n1 and n2 are greater than root, then LCA lies in right
if (node.data < n1 && node.data < n2)
return lca(node.right, n1, n2);
return node;
}
/* Driver program to test lca() */
public static void main(String args[])
{
// Let us construct the BST shown in the above figure
BinaryTree tree = new BinaryTree();
tree.root = new Node(20);
tree.root.left = new Node(8);
tree.root.right = new Node(22);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(12);
tree.root.left.right.left = new Node(10);
tree.root.left.right.right = new Node(14);
int n1 = 10, n2 = 14;
Node t = tree.lca(tree.root, n1, n2);
System.out.println("LCA of " + n1 + " and " + n2 + " is " + t.data);
n1 = 14;
n2 = 8;
t = tree.lca(tree.root, n1, n2);
System.out.println("LCA of " + n1 + " and " + n2 + " is " + t.data);
n1 = 10;
n2 = 22;
t = tree.lca(tree.root, n1, n2);
System.out.println("LCA of " + n1 + " and " + n2 + " is " + t.data);
}
}
Q35. Rotate the list that is given, to the right by k places, which is non-negative.
class LinkedList {
Node head; // head of list
/* Linked list Node*/
class Node {
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
// This function rotates a linked list counter-clockwise
// and updates the head. The function assumes that k is
// smaller than size of linked list. It doesn't modify
// the list if k is greater than or equal to size
void rotate(int k)
{
if (k == 0)
return;
// Let us understand the below code for example k = 4
// and list = 10->20->30->40->50->60.
Node current = head;
// current will either point to kth or NULL after this
// loop. current will point to node 40 in the above example
int count = 1;
while (count < k && current != null) {
current = current.next;
count++;
}
// If current is NULL, k is greater than or equal to count
// of nodes in linked list. Don't change the list in this case
if (current == null)
return;
// current points to kth node. Store it in a variable.
// kthNode points to node 40 in the above example
Node kthNode = current;
// current will point to last node after this loop
// current will point to node 60 in the above example
while (current.next != null)
current = current.next;
// Change next of last node to previous head
// Next of 60 is now changed to node 10
current.next = head;
// Change head to (k+1)th node
// head is now changed to node 50
head = kthNode.next;
// change next of kth node to null
kthNode.next = null;
}
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
/* 3. Make next of new Node as head */
new_node.next = head;
/* 4. Move the head to point to new Node */
head = new_node;
}
void printList()
{
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
/* Driver program to test above functions */
public static void main(String args[])
{
LinkedList llist = new LinkedList();
// create a list 10->20->30->40->50->60
for (int i = 60; i >= 10; i -= 10)
llist.push(i);
System.out.println("Given list");
llist.printList();
llist.rotate(4);
System.out.println("Rotated Linked List");
llist.printList();
}
} /*
Q36. Write a function that counts the total set of bits in a 32-bit integer.
import java.io.*;
class countSetBits {
/* Function to get no of set
bits in binary representation
of positive integer n */
static int countSetBits(int n)
{
int count = 0;
while (n > 0) {
count += n & 1;
n >>= 1;
}
return count;
}
// driver program
public static void main(String args[])
{
int i = 9;
System.out.println(countSetBits(i));
}
}
Q37. How do you detect a loop in a singly linked list?
import java.util.*;
public class LinkedList {
static Node head; // head of list
/* Linked list Node*/
static class Node {
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
/* Inserts a new Node at front of the list. */
static public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
/* 3. Make next of new Node as head */
new_node.next = head;
/* 4. Move the head to point to new Node */
head = new_node;
}
// Returns true if there is a loop in linked
// list else returns false.
static boolean detectLoop(Node h)
{
HashSet s = new HashSet();
while (h != null) {
// If we have already has this node
// in hashmap it means their is a cycle
// (Because you we encountering the
// node second time).
if (s.contains(h))
return true;
// If we are seeing the node for
// the first time, insert it in hash
s.add(h);
h = h.next;
}
return false;
}
/* Driver program to test above function */
public static void main(String[] args)
{
LinkedList llist = new LinkedList();
llist.push(20);
llist.push(4);
llist.push(15);
llist.push(10);
/*Create loop for testing */
llist.head.next.next.next.next = llist.head;
if (detectLoop(head))
System.out.println("Loop found");
else
System.out.println("No Loop");
}
}
Q38. Find the smallest window in a string consisting of all the characters from another string
// Java program to find smallest
// window containing
// all characters of a pattern.
public class GFG {
static final int no_of_chars = 256;
// Function to find smallest
// window containing
// all characters of 'pat'
static String findSubString(String str, String pat)
{
int len1 = str.length();
int len2 = pat.length();
// Check if string's length is
// less than pattern's
// length. If yes then no such
// window can exist
if (len1 < len2) {
System.out.println("No such window exists");
return "";
}
int hash_pat[] = new int[no_of_chars];
int hash_str[] = new int[no_of_chars];
// Store occurrence ofs
// characters of pattern
for (int i = 0; i < len2; i++)
hash_pat[pat.charAt(i)]++;
int start = 0, start_index = -1,
min_len = Integer.MAX_VALUE;
// Start traversing the string
// Count of characters
int count = 0;
for (int j = 0; j < len1; j++) {
// Count occurrence of characters
// of string
hash_str[str.charAt(j)]++;
// If string's char matches
// with pattern's char
// then increment count
if (hash_str[str.charAt(j)]
<= hash_pat[str.charAt(j)])
count++;
// If all the characters are matched
if (count == len2) {
// Try to minimize the window
while (hash_str[str.charAt(start)]
> hash_pat[str.charAt(start)]
|| hash_pat[str.charAt(start)]
== 0) {
if (hash_str[str.charAt(start)]
> hash_pat[str.charAt(start)])
hash_str[str.charAt(start)]--;
start++;
}
// update window size
int len_window = j - start + 1;
if (min_len > len_window) {
min_len = len_window;
start_index = start;
}
}
}
// If no window found
if (start_index == -1) {
System.out.println("No such window exists");
return "";
}
// Return substring starting
// from start_index
// and length min_len
return str.substring(start_index,
start_index + min_len);
}
// Driver Method
public static void main(String[] args)
{
String str = "this is a test string";
String pat = "tist";
System.out.print("Smallest window is :\n "
+ findSubString(str, pat));
}
}
Q39. What is the minimum number of swaps required for arranging pairs?
class GFG {
// This function updates indexes
// of elements 'a' and 'b'
static void updateindex(int index[], int a,
int ai, int b, int bi)
{
index[a] = ai;
index[b] = bi;
}
// This function returns minimum number
// of swaps required to arrange
// all elements of arr[i..n] become arranged
static int minSwapsUtil(int arr[], int pairs[],
int index[], int i, int n)
{
// If all pairs processed so
// no swapping needed return 0
if (i > n)
return 0;
// If current pair is valid so
// DO NOT DISTURB this pair
// and move ahead.
if (pairs[arr[i]] == arr[i + 1])
return minSwapsUtil(arr, pairs, index, i + 2, n);
// If we reach here, then arr[i] and
// arr[i+1] don't form a pair
// Swap pair of arr[i] with arr[i+1]
// and recursively compute minimum swap
// required if this move is made.
int one = arr[i + 1];
int indextwo = i + 1;
int indexone = index[pairs[arr[i]]];
int two = arr[index[pairs[arr[i]]]];
arr[i + 1] = arr[i + 1] ^ arr[indexone] ^
(arr[indexone] = arr[i + 1]);
updateindex(index, one, indexone, two, indextwo);
int a = minSwapsUtil(arr, pairs, index, i + 2, n);
// Backtrack to previous configuration.
// Also restore the previous
// indices, of one and two
arr[i + 1] = arr[i + 1] ^ arr[indexone] ^
(arr[indexone] = arr[i + 1]);
updateindex(index, one, indextwo, two, indexone);
one = arr[i];
indexone = index[pairs[arr[i + 1]]];
// Now swap arr[i] with pair of arr[i+1]
// and recursively compute minimum swaps
// required for the subproblem
// after this move
two = arr[index[pairs[arr[i + 1]]]];
indextwo = i;
arr[i] = arr[i] ^ arr[indexone] ^ (arr[indexone] = arr[i]);
updateindex(index, one, indexone, two, indextwo);
int b = minSwapsUtil(arr, pairs, index, i + 2, n);
// Backtrack to previous configuration. Also restore
// the previous indices, of one and two
arr[i] = arr[i] ^ arr[indexone] ^ (arr[indexone] = arr[i]);
updateindex(index, one, indextwo, two, indexone);
// Return minimum of two cases
return 1 + Math.min(a, b);
}
// Returns minimum swaps required
static int minSwaps(int n, int pairs[], int arr[])
{
// To store indices of array elements
int index[] = new int[2 * n + 1];
// Store index of each element in array index
for (int i = 1; i <= 2 * n; i++)
index[arr[i]] = i;
// Call the recursive function
return minSwapsUtil(arr, pairs, index, 1, 2 * n);
}
// Driver code
public static void main(String[] args) {
// For simplicity, it is assumed that arr[0] is
// not used. The elements from index 1 to n are
// only valid elements
int arr[] = {0, 3, 5, 6, 4, 1, 2};
// if (a, b) is pair than we have assigned elements
// in array such that pairs[a] = b and pairs[b] = a
int pairs[] = {0, 3, 6, 1, 5, 4, 2};
int m = pairs.length;
// Number of pairs n is half of total elements
int n = m / 2;
// If there are n elements in array, then
// there are n pairs
System.out.print("Min swaps required is " +
minSwaps(n, pairs, arr));
}
}
Q40. Given a binary tree, find the minimum root-to-leaf height.
/* Class containing left and right child of current
node and key value*/
class Node
{
int data;
Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
public class BinaryTree
{
//Root of the Binary Tree
Node root;
int minimumDepth()
{
return minimumDepth(root);
}
/* Function to calculate the minimum depth of the tree */
int minimumDepth(Node root)
{
// Corner case. Should never be hit unless the code is
// called on root = NULL
if (root == null)
return 0;
// Base case : Leaf Node. This accounts for height = 1.
if (root.left == null && root.right == null)
return 1;
// If left subtree is NULL, recur for right subtree
if (root.left == null)
return minimumDepth(root.right) + 1;
// If right subtree is NULL, recur for left subtree
if (root.right == null)
return minimumDepth(root.left) + 1;
return Math.min(minimumDepth(root.left),
minimumDepth(root.right)) + 1;
}
/* Driver program to test above functions */
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
System.out.println("The minimum depth of "+
"binary tree is : " + tree.minimumDepth());
}
}
Q41. How to reach the min Cost path?
public class GFG {
/* A utility function that returns
minimum of 3 integers */
static int min(int x, int y, int z)
{
if (x < y)
return (x < z) ? x : z;
else
return (y < z) ? y : z;
}
/* Returns cost of minimum cost path
from (0,0) to (m, n) in mat[R][C]*/
static int minCost(int cost[][], int m,
int n)
{
if (n < 0 || m < 0)
return Integer.MAX_VALUE;
else if (m == 0 && n == 0)
return cost[m][n];
else
return cost[m][n] +
min( minCost(cost, m-1, n-1),
minCost(cost, m-1, n),
minCost(cost, m, n-1) );
}
// Driver code
public static void main(String args[])
{
int cost[][] = { {1, 2, 3},
{4, 8, 2},
{1, 5, 3} };
System.out.print(minCost(cost, 2, 2));
}
}
Q42. Write the function to show Maximum Subarray Problem.
public int maxSubArray(int[] nums) {
int n = nums.length;
int maximumSubArraySum = Integer.MIN_VALUE;
int start = 0;
int end = 0;
for (int left = 0; left < n; left++) {
int runningWindowSum = 0;
for (int right = left; right < n; right++) {
runningWindowSum += nums[right];
if (runningWindowSum > maximumSubArraySum) {
maximumSubArraySum = runningWindowSum;
start = left;
end = right;
}
}
}
logger.info("Found Maximum Subarray between {} and {}", start, end);
return maximumSubArraySum;
}
Q43. Give the code that shows Palindrome Partitioning.
// Palindrome PartitioningProblem
public class GFG
{
static boolean isPalindrome(String string, int i, int j)
{
while(i < j)
{
if(string.charAt(i) != string.charAt(j))
return false;
i++;
j--;
}
return true;
}
static int minPalPartion(String string, int i, int j)
{
if( i >= j || isPalindrome(string, i, j) )
return 0;
int ans = Integer.MAX_VALUE, count;
for(int k = i; k < j; k++)
{
count = minPalPartion(string, i, k) +
minPalPartion(string, k + 1, j) + 1;
ans = Math.min(ans, count);
}
return ans;
}
// Driver code
public static void main(String args[])
{
String str = "ababbbabbababa";
System.out.println("Min cuts needed for "
+ "Palindrome Partitioning is " + minPalPartion(str, 0, str.length() - 1));
}
}
Amazon is known to hire exceptional talent so your performance bar should be higher than the status quo. Any sort of poor performance while answering Amazon interview questions might hurt your chances of clearing the interview. At Unstop Pro, we have put together a detailed guide on the Amazon hiring drive. We'll cover the following in our interview preparation courses:
- Amazon’s hiring approach
- Application process and timeline
- Hiring Process
- Preparation tips
- Important questions
You can plan ahead and prepare for the position you aspire for. Present yourself with confidence and be open to feedback. #BeUnstoppable
You may also like to read:
Comments
Add commentLogin to continue reading
And access exclusive content, personalized recommendations, and career-boosting opportunities.
Shahnawaz shaan 6 months ago