Log In

Don't have an account? Sign up now

Lost Password?

Sign Up

Prev Next

Amazon Interview Guide

Amazon Hiring Process

Amazon SDE1 Recruitment Overview

Amazon’s hiring cycle for Software Development Engineer 1 (SDE1) includes four major rounds:

  1. Online Assessment
  2. Technical Interview Round 1
  3. Technical Interview Round 2
  4. Bar Raiser Round

Ways Amazon Hires

Amazon recruits candidates through three main channels:

  • Campus Recruitment (primarily from Tier-1 colleges)
  • Off-Campus Drives (mainly for Tier-2/3 colleges)
  • Referral-Based Hiring

Roles Offered

Amazon offers multiple technical roles depending on a candidate’s skills, such as:

  • Quality Assurance Engineer – ~24 LPA
  • Support Engineer – ~18.9 LPA
  • Software Development Engineer in Test (SDET) – ~22.5 LPA
  • System Development Engineer – ~31.5 LPA
  • Programmer Analyst – ~18 LPA
  • Data Engineer – ~28 LPA

Note: Salary packages vary year to year depending on Amazon’s financial performance.


Salary Structure

Below is a paraphrased breakdown of Amazon’s compensation and internship details for various roles.

  • System Development Engineer
    • Before full-time employment, candidates are usually offered an internship with a stipend of ₹20,000.
  • SDET – 1 (Software Development Engineer in Test)
    • Interns receive ₹60,000 before converting to full-time.
  • Quality Assurance Engineer
    • Internship stipend: ₹20,000
  • Data Engineer
    • Internship stipend: ₹20,000
  • Support Engineer
    • Internship stipend: ₹20,000

Detailed Amazon Hiring Process

1. Online Assessment (OA)

This is the toughest elimination stage, removing around 70% of applicants.
It typically takes place on Hackerrank, though the platform may vary for some colleges or job roles.

The OA consists of four sections:

Aptitude Test (usually skipped in on-campus hiring)

Includes basic questions from quantitative aptitude, verbal ability, and logical reasoning. Difficulty: easy.

Technical MCQs (also often skipped for on-campus drives)

Covers C/C++, Operating Systems, Computer Networks, DBMS, and Data Structures.

Automata Fix (optional for on-campus)

Applicants must correct or complete given code snippets. Usually 7 problems.

Coding Round (mandatory)

Two coding challenges of medium to difficult level.


2. Technical Interview Round 1

Elimination Rate: 80% of remaining candidates

  • Conducted by an SDE with 3–5 years of experience.
  • Focuses on fundamentals of programming, basic DSA, and computer science concepts.
  • Questions are usually easy to moderate.
  • Expected duration: up to 1 hour, though unsuitable candidates may be filtered out earlier (20 minutes).

3. Technical Interview Round 2

Elimination Rate: Over 90% of those who pass Round 1

  • Taken by a senior manager (7–10 years of experience).
  • Starts with advanced DSA problems and detailed coding exercises.
    The candidate may be asked to explain multiple approaches.
  • Then shifts to projects, internships, and certifications.
    Expect deep-dive discussions, code walkthroughs, and possibly a live project demo.
  • This round often extends beyond an hour due to its detail-oriented nature.

4. Bar Raiser Round

Elimination Rate: ~95%

The Bar Raiser evaluates cultural fit and behavioral traits based on Amazon’s 16 Leadership Principles.
This round is similar to an HR interview but much more rigorous.


Amazon’s 16 Leadership Principles

Along with the typical questions asked


1. Customer Obsession

Amazon prioritizes customers in every decision.
Sample Questions:

  • How have you delighted customers previously?
  • Describe a time you used customer feedback to enhance a product.
  • How do you react to criticism from customers?

2. Ownership

Employees are expected to take responsibility beyond their job description.
Questions:

  • Describe creative solutions you’ve proposed.
  • Tell me about a time you took ownership when a team didn’t meet expectations.

3. Invent and Simplify

Amazon values innovation and simpler processes.
Questions:

  • Share a scenario where you had to innovate.
  • Have you ever designed a new method instead of following the standard one?

4. Are Right, A Lot

Leaders must show good judgment and make strong decisions.
Questions:

  • Recall a moment when you made a fast decision under pressure.
  • Describe a choice that negatively impacted your project.

5. Learn and Be Curious

Amazon prefers candidates who continually upgrade their knowledge.
Questions:

  • What did you study recently on your own?
  • What are your future learning plans?

6. Hire and Develop the Best

Leaders identify and mentor high-potential individuals.
Questions:

  • Have you ever guided or trained juniors?
  • How do you evaluate candidates?

7. Insist on the Highest Standards

Amazon leaders set and maintain high-quality standards.
Questions:

  • Describe a time you were dissatisfied with work quality.
  • How do you ensure excellence?

8. Think Big

Amazon values people who envision large-scale solutions.
Questions:

  • Describe a time you took an unconventional route to solve a problem.
  • How do you avoid losing sight of long-term goals?

9. Bias for Action

Decisions must be taken quickly even with partial information.
Questions:

  • Do you take calculated risks?
  • Give an example of a decision made with limited data.

10. Frugality

Amazon prefers maximizing output with minimum resources.
Questions:

  • How do you plan budgets for projects?
  • Tell me about a time you worked with limited manpower.

11. Earn Trust

Honesty and respect foster trust.
Questions:

  • How do you build trust with team members?
  • How do you give feedback without offending others?

12. Dive Deep

Leaders must thoroughly understand problems and details.
Questions:

  • How do you track day-to-day tasks?
  • How do you identify root causes?

13. Have Backbone; Disagree and Commit

Leaders respectfully challenge decisions when required.
Questions:

  • When did you disagree with a superior?
  • How do you stand your ground professionally?

14. Deliver Results

Despite obstacles, leaders must accomplish goals.
Questions:

  • How did you handle a project with limited resources?
  • When did you find an alternative approach to deliver results?

15. Strive to be Earth’s Best Employer

Leaders must foster a positive and inclusive workplace.
Questions:

  • What steps would you take to improve team morale?
  • How would you enhance workplace culture?

16. Success and Scale Bring Broad Responsibility

Leaders remain humble and use their influence to create a positive impact.
Questions:

  • Describe an initiative to improve your work environment.
  • How do you stay grounded after success?

About Amazon

  • Amazon was founded by Jeff Bezos on July 5th, 1994 in Seattle, Washington.
  • The company began as an online bookstore.
  • Amazon Web Services (AWS) launched in 2006.
  • Its headquarters remain in Seattle, but it operates worldwide.
  • Andy Jassy is the current CEO, taking over from Bezos after his 20-year tenure.
  • Amazon’s business spans:
    • E-commerce
    • Cloud computing
    • Digital streaming
    • Artificial Intelligence

50 Most asked Amazon interview Questions

Question 1:

Do you have any technical certifications?

Explanation:

  • If you have listed certifications in your resume, the interviewer will ask this question.
  • Describe the certifications in detail, including your training, projects, seminars, webinars etc.
  • List only those certifications that are relevant to the job. And co-relate how your certification can help in the job.

Question 2:

What is the extent of your technical expertise?

Explanation:

  • You have to rate your technical skills.
  • The interviewer wants to check how in touch you are with the current technologies.
  • Mention the technologies you have worked with, and how good you are with them.
  • Additionally mentioning technologies like ML, AL, AWS etc which are the most sought after technologies right now will earn you more points.
  • However do not lie, cause they will cross check your answers.

Question 3:

What do you do to improve your technical skills?

Explanation:

  • An employee who is always striving to better themselves, is a valuable asset.
  • The interviewer wants to know how you have tried to better yourself and skills.

Mention methods like :-

  • Reading technical books and journals. (mention the names of a few)
  • Attend online webinars and tutorials regarding the skills.
  • Build a git-hub profile(show your projects to the interviewer)
  • Learning new tools

Question 4:

Give an example of how you apply your technical knowledge in a practical way?

Explanation:

  • This is a behavioral interview type question.
  • You can follow the STAR method to answer questions of this type.
  • Follow the framework and explain how you have applied your technical skills in any project or product. How you did it and what were the results.

Question 5:

What was the recent technical project you worked on? What were your key responsibilities?

Explanation:

  • This is a behavioral interview type question.
  • If you have worked on a project that used the same technologies that were mentioned in the job description/eligibility criteria, try to mention that.
  • Else you can mention any other project.
  • Use the STAR method to answer questions of this type.
  • If the interviewer has mentioned a specific part like your responsibilities, or the challenges you faced, describe that part with more emphasis.

Question 6:

What is the production deployment process you follow?

Explanation:

  • Deployment is the step by step process of making an application ready.
  • It varies from individual to individual and organization to organization.
  • Some of the common models are Waterfall Model, Iterative Model, Agile Model etc.
  • You can follow one of these, or if you have your own mix you can talk about that.
  • Explain your thought process to the interviewer.

Question 7:

What do you like most about the IT industry? What do you enjoy the least about it?

Explanation:

  • Mention the features of IT that you like.
  • For instance you can mention that being able to work with emerging technologies is your favorite feature.
  • Also mention the aspects that you wish would change.

Question 8:

Why is a solution design document important?

Explanation:

  • Solution design document is a document on which the details of a project are written before its implementation.
  • It’s an important document to communicate the technical details of the plan to a team.
  • It also helps organize one’s thoughts before you start working on the project.

Question 9:

Whenever you solve a problem, who do you keep in mind? The end-user, the business, or yourself, and why?

Explanation:

  • The aim of any product is to be of service to someone.
  • It could be the user, the company or the creator.
  • Mention who you think is the one of service.
  • Explain who is the main benefactor for the product developed by you.

Question 10:

How many programming languages do you know?

Explanation:

  • Whatever languages you have mentioned in your resume, tell them here.
  • Sometimes interviewers will ask you to rate yourselves, in the languages you mentioned.
  • Do not rank yourself very high like a 9, because they might ask you advanced level questions which if you are unable to answer will create a negative impression.
  • Whichever language you rate yourself highest in the follow up questions will be mostly from there only.
  • They will also ask questions as to why you prefer that language in particular or why you are stronger there.

Question 11:

What is the use of printf() and scanf() functions?

Explanation:

  • printf() function displays integer, character, float or string values on the screen.
  • %d-displays an integer value
  • %s-displays a string
  • %c-displays a character value
  • %f-displays a floating value.
  • scanf() function takes input from the user.

Question 12:

What is the static variable? What is its use?

Explanation:

A variable which is declared static, is known as a static variable. These variables are able to retain its value between multiple function calls.

Syntax:

static int y=10;//static variable

Static variables are used because these variables can be accessed from anywhere in the program.

Static variables are used as common values and are shared by all the methods.


Question 13:

What is the difference between call by value and call by reference in C?

Explanation:


Question 14:

What is Recursion in C?

Explanation:

Recursion is the process where a function calls itself. This function is known as a recursive function. There are 2 phases of recursion:-

  • Winding phase – when a recursive function calls itself, this phase reaches its end when the condition is fulfilled.
  • Unwinding phase – when the condition is fulfilled, this phase starts and the control is returned to the original call.

Question 15:

What is a pointer in C? What are its uses?

Explanation:

A pointer is a variable referring to the address of a value. When a variable is declared inside a program, the system allocates some memory to it. This memory contains an address number. The variables that hold this address number are called pointer variables.

Syntax: Data_type *p;

P is a pointer variable holding the address number of data_type value.

  Uses of Pointer:-

Pointers are used in accessing elements through an array.  Pointers are used to pass a reference of a variable to another function.


Question 16:

What is a NULL pointer and far pointer?

Explanation:

  • Null Pointer – Null pointer is a pointer that does not refer to any address of value but to NULL.  When “0” is assigned to a pointer of any type, it creates a Null pointer.
  • Far Pointer – A far pointer is a pointer that can access all the 16 segments, i.e. the whole residence memory of the RAM.  It is a 32 bit pointer that obtains information from outside the memory in a given section.

Question 17:

What is a dangling pointer? How is it overcome?

Explanation:

Dangling pointer is a problem that arises when an object is deleted without modifying the value of the pointer. Thus the pointer is now pointing to a deallocated memory.

In other words, if a pointer say A is pointing to a memory location, but another pointer B deletes the memory occupied by A while A is still pointing to that location, A becomes a dangling pointer.

  • The problem is overcome by assigning a NULL value to the dangling pointer.
  • After de-allocating the memory from a pointer variable, the pointer is assigned to a NULL value.
  • Thus the pointer is not pointing to any memory location, therefore it’s no longer a dangling pointer.

Question 18:

What is an infinite loop?

Explanation:

A loop running continuously for an indefinite number of times is called the infinite loop.


Question 19:

What is a command line argument?

Explanation:

The argument passed to the main() function while executing the program is known as a command line argument.


Question 20:

Can we compile a program without the main() function?

Explanation:

We can compile a program without the main() function, however the program won’t be executed. However adding #define, we can compile and run the program without using the main() function.


Question 21:

What is an object and class?

Explanation:

  • Object – It is a collection of methods and classes which represent its state and execute operations.
  • Class – It is used to define new types of data which is then used to create objects.

Question 22:

What do you mean by JVM, JDK and JRE?

Explanation:

  • JVM – Java Virtual Machine. Offers runtime environment for cods to be executed.
  • JRE – Java Runtime Environment. It’s the collection of files that are needed during runtime by JVM.
  • JDK – Java Development Kit. It is a kit which contains the tools necessary to write and execute a program.

Question 23:

How can you restrict inheritance?

Explanation:

By the following methods:

  • Using the final keyword.
  • Making the method final.
  • Using private constructor.
  • Using (//) Javadoc comment

Question 24:

What are static methods and static variables?

Explanation:

They are methods and variables shared by all the objects in a class. Their static nature comes from the class and not from the object itself.


Question 25:

What is enumeration?

Explanation:

It is an interface you can use to access original data structure.


Question 26:

What is the use of ‘this’ keyword in JAVA?

Explanation:

‘this’ keyword is used to refer to a current object, to invoke the current class method or class constructor.

It is also used to pass on as an argument into methods or constructors.


Question 27:

What is the final variable?

Explanation:

In Java, the  final variable is used to restrict the users from updating the variable.  The final variable once assigned can not be changed after that.


Question 28:

Why is JAVA platform independent?

Explanation:

Java is platform independent because of its byte codes which can run on any system regardless of its operating systems.


Question 29:

What are access modifiers in Java?

Explanation:

Access modifiers are special keywords that can restrict the access of a class, constructor, data member and method in another class. They are of 4 types:-

  • Default
  • Private
  • Protected
  • Public.

Question 30:

What is method overloading?

Explanation:

It is a polymorphism technique that allows us to create multiple methods with the same name but different signatures.


Question 31:

What is interpreted language?

Explanation:

An interpreted language executes its statements line by line. Interpreted language codes can run directly from the source code with no intermediary compilation step.


Question 32:

What are lists and tuples?

Explanation:

Lists and tuples are sequence data types.  The objects stored in both the sequences can have different data types.

  • List are represented by square brackets [“”,’’]
  • Tuples are represented by round brackets (“”,””)
  • The difference between the two is that lists are mutable while tuples are immutable. Which means that lists can be modified while tuples can not be modified.

Question 33:

What is pass in Python?

Explanation:

Pass keyword represents a null operation in python. Used for the purpose of filling up empty block code which may execute during runtime, but are yet to be written


Question 34:

What is self in Python?

Explanation:

Self is a keyword that defines an instance of an object of a class. It is explicitly used as the first parameter.


Question 35:

What is slicing in Python?

Explanation:

Slicing is used to break up a list or tuple.

  • Start: it is the starting index from where the list is sliced
  • Stop: It is the ending index where the list is stop
  • Step: It is the number of steps to jump

Syntax:

[start:stop:step]


Question 36:

What is the use of break statement?

Explanation:

  • It is used to terminate the execution of the current loop.
  • Break statement, breaks the current execution and transfer control to outside the current block.

Question 37:

What is an operator in Python?

Explanation:

Operator is a symbol, which is used on some values and produces an output as a result. Operator works on operands.

Operators are of unary, binary or ternary types depending on the number of operands required.

They include:-

  • Arithmetic
  • Relational
  • Assignment
  • Logical
  • Identify
  • Bitwise

Question 38:

What is swapcase() function in Python?

Explanation:

  • It is a string function which converts all uppercase characters into lowercase and vice versa.
  • It is used for altering the existing case of the string.
  • This method creates a copy of the string which contains all the characters in the swap case.

Question 39:

What is the  Python decorator?

Explanation:

It is a powerful tool that allows you to add functionality in an existing code. It is also known as meta-programming.


Question 40:

What is the difference between Python Arrays and lists?

Explanation:


Question 41:

What is DBMS?

Explanation:

DBMS stands for Database Management System. It carries out operations like creation, maintenance and use of a database.


Question 42:

What are tables, fields and record?

Explanation:

  • Tables: Data organized in a model with Rows and Columns is called a table. Rows are horizontal while tables are vertical.
  • Fields: In a table there are a specified number of columns known as fields.
  • Records: There are infinite number of rows which is called a record.

Question 43:

What is Foreign Key?

Explanation:

Foreign Key is a key which links 2 tables.

It is a field or a collection of fields in a table that corresponds to the Primary Key of another table.


Question 44:

What is the difference between DELETE and TRUNCATE?

Explanation:


Question 45:

What is a constraint?

Explanation:

Constraints are limitations on the data type of a given table. Samples of constraints are:

  • Not Null
  • Check
  • Default

Question 46:

What is ACID property in a database?

Explanation:

  • Atomicity – It states each transaction is all or nothing. If one part of the transaction fails, the entire transaction fails.
  • Consistency – It states that data must follow all validation rules. A transaction never leaves the database without being completed.
  • Isolation – Isolation provides concurrency control. It ensures that concurrent property of execution should not be met.
  • Durability – Once a transaction is committed it will remain committed regardless of the situation, power loss, crashes etc.

Question 47:

What is SQL?

Explanation:

SQL stands for Structured Query Language and is used to communicate with the Database. It is a standard language for accessing and manipulating databases.


Question 48:

What is a unique key?

Explanation:

  • A Unique key constraint identifies each record in the database. It provides for the column or set of columns.
  • A unique key is a set of one or more than one field of a table that can uniquely identify a record in a database table.

Question 49:

What is a relationship and what are they?

Explanation:

Relationship is the interconnection of tables within the database. There are various relationships,

  • One to One Relationship.
  • One to Many Relationship.
  • Many to One Relationship.
  • Self-Referencing Relationship.

Question 50:

What is a query?

Explanation:

A query is really a request for data. A DB query is a code written in order to get the information back from the database. You ask the database for something and it answers in the best way it knows with data as a result of a query.


Question 51:

What is Machine Learning?

Explanation:

Machine Learning is the science of getting computers to act in a real-time situation without being programmed explicitly. It is an application of AI and it enables systems to learn automatically and to improve from previous experience.


Question 52:

What is Supervised, Unsupervised and Semi-Supervised learning?

Explanation:

  • Supervised learning – The model is trained on labeled data, and then it predicts based on the labeled data, Therefore it requires a supervisor to train the data.
  • Unsupervised learning – The model is trained on unlabeled data. The model tries to find patterns and relationships in the data and classify them accordingly.
  • Semi-Supervised Learning – It uses some amount of labeled data and a large amount of unlabeled data. The goal is to classify unlabeled data with the help of labeled data.

Question 53:

What are training set and test set in Machine Learning and why are they important?

Explanation:

  • Training set is a set given to the model for training, analyzing and learning.
  • Test set is a set used for testing the model locally before using it in a real time application.

Question 54:

Explain the stages of building a Machine Learning model.

Explanation:

  • Data Collection: Appropriate data is collected using either some algorithm or manually.
  • Data Processing: The collected data is processed by handling all the null values, categories etc.
  • Model Building: The algorithms to create the model is decided and built.
  • Model Evaluation: The model is evaluated using techniques such as accuracy score, z score etc.
  • Model Saving and Testing: The model is saved for future use and real time testing is done.

Question 55:

How does IoT work?

Explanation:

Iot is built on the concept of AI. An IoT device has a sensor which collects data, the cloud facilitates the network between the devices, the software processes and stores the data and finally the UI enables the device to respond to the stimulation.


Question 56:

What is Natural Language Processing?

Explanation:

Natural language processing is a branch of Artificial Intelligence that deals with the conversion of Human Language to Machine Understandable language, so it can be processed by Machine Learning models.


Question 57:

What is IIOT?

Explanation:

IIOT(Industrial Internet of Things) are large scale IoT structures or systems that are used at the industrial level.


Question 58:

What is Deep Learning?

Explanation:

Deep Learning is a subset of machine learning. It is a neural network with multiple layers, which creates a stimulation of the human brain, allowing the model to lean from large amounts of data.


Question 59:

What is Arduino?

Explanation:

It is an open source electronics platform based on easy-to-use hardware and software. Arduino boards can read input and turn it into an output.


Question 60:

What is Neural Network?

Explanation:

Neural Network is a replication of the firing of neurons in our brain, which facilitates learning, although on a less complex scale.


Question 61:

What do you mean by Open-source Hardware?

Explanation:

  • Open source hardware is similar to open source software.
  • Ardunio is open source. The source code for which the Java environment is released under the GPL and C/C++ is under LGPL.

Question 62:

What is Raspberry Pi?

Explanation:

Raspberry Pi is a microcomputer that can be connected to a peripheral device. We can execute a number of tasks in a Raspberry Pi including, creating spreadsheets,  coding, games etc.


Question 63:

How is Raspberry Pi used in IoT?

Explanation:

Raspberry Pi is a platform to develop many IoT based applications. IoT requires a network of devices and software to connect and exchange data. Raspberry Pi can provide this platform for it.


Question 64:

List any two real-life applications of Natural language processing.

Explanation:

  • Google Translate
  • Chat bots
  • Siri, Alexa

Question 65:

What is Ethical Hacking?

Explanation:

Ethical Hacking is when a person is allowed to hack the system with the permission of the owner to find any bug in the system and to fix it.


Question 66:

What is the difference between IP and MAC address?

Explanation:

  • IP Address –  IP address is assigned to a device so that it can be located on the network.
  • MAC Address – MAC Address is a unique serial number assigned to every network interface on every device.

Question 67:

Explain LAN

Explanation:

LAN or Local Area Network is used to connect devices such that they are able to share resources and exchange information. LAN is of two types, wireless LAN and wired LAN.


Question 68:

What is VPN?

Explanation:

VPN or Virtual Private Network is a private Wide Area Network built on the Internet. It allows the creation of a secured tunnel between different networks using the internet. VPN allows a client to connect to a network remotely.


Question 69:

What are Private and Special IP addresses?

Explanation:

  • Private Address: These are specific IPs that are reserved specifically for private use only. These are non rout-able and cannot be used by the devices on the internet.
  • Special Address: IP Range from 127.0.0.1 to 127.255.255.255 are network testing addresses also known as loop-back addresses. These are the special IP addresses.

Question 70:

What is DNS?

Explanation:

DNS is the Domain Name System. It basically translates the domain name of their corresponding IPs. It uses port 53 by default.


Question 71:

What is the main purpose of an OS? What are the different types of OS?

Explanation:

The function of an OS is to execute user programs and make it easier for the users to interact with the system. It is designed to ensure that the system performs better by managing all computational activities.

Types of OS:

  • Batched OS (Example: Payroll System, Transactions Process, etc.
  • Multi-Programmed OS (Example: Windows O/S, UNIX O/S, etc.)
  • Timesharing OS (Example: Multics, etc.
  • Distributed OS (LOCUS, etc.)
  • Real-Time OS (PSOS, VRTX, etc.)

Question 72:

What is GUI?

Explanation:

GUI or Graphical User Interface is an interface that allows users to use graphics to interact with the OS. Its function is to make the OS more user friendly and less complex.  Instead of having to memorize commands, users can just click on a button and execute the procedure.


Question 73:

What do you mean by RTOS?

Explanation:

Real Time Operating System of RTOS is a type of OS used for real time applications. It is used for tasks that are needed to be executed within a short period of time. It’s designed for applications where data processing should be done in a fixed and small measure of time.


Question 74:

Name some of the most famous OS.

Explanation:

  • MS-Windows
  • Ubuntu
  • Mac OS
  • Fedora
  • Solaris
  • Free BSD
  • Chrome OS
  • CentOS
  • Debian
  • Android

Question 75:

What is IPC?

Explanation:

IPC or Interprocess Communication is a mechanism that requires the use of resources like memory that is shared between processes or threads. With IPC, the OS allows different processes to communicate with each other.  It is simply used for exchanging data between multiple threads in one or more programs or processes.

Amazon top 20 technical interview questions

Question 1:

What is the working of the stack while calling a function?

Answer:

When a function is called, the stack performs the following operations:

  • Push space for return variables.
  • Push parameters in the stack.
  • Push local variable of the function.
  • Adds stack frame.

Question 2:

What is Deep Learning?

Answer:

Deep Learning is a subset of machine learning. It is a neural network with multiple layers, which creates a stimulation of the human brain, allowing the model to lean from large amounts of data.


Question 3:

What are the Semaphores?

Answer:

Semaphore is an integer variable or procedure synchronization device which is used to solve critical section problems by using two atomic operations: wait(p) and signal(v). There is no wastage of resources because of busy waiting in semaphores as the processor time is not wasted in checking whether the process can access the n critical section or not. Therefore it allows only one process into the critical section and follows the mutual exclusion principle.


Question 4:

Implement queues using linked lists.

Answer:

public class unstop

{

 private Node front, rear;

 private int s; // number of items

 //class to define linked node

 private class Node

 {

 int data;

 Node next;

 }


 public unstop()

 {

 front = null;

 rear = null;

 s = 0;

 }

 public boolean isEmpty()

 {

 return (s == 0);

 }

 //to Remove item

 public int dequeue()

 {

 int data = front.data;

 front = front.next;

 if (isEmpty())

 {

 rear = null;

 }

 s–;

 System.out.println(data+ ” removed from the queue”);

 return data;

 }

 //to Add data .

 public void enqueue(int data)

 {

 Node old = rear;

 rear = new Node();

 rear.data = data;

 rear.next = null;

 if (isEmpty())

 {

 front = rear;

 }

 else

 {

 old.next = rear;

 }

 s++;

 System.out.println(data+ ” added to the queue”);

 }

 public static void main(String args[]){

 unstop queue = new unstop();

 queue.enqueue(1);

 queue.dequeue();

 queue.enqueue(2);

 queue.enqueue(3);

 queue.enqueue(4);

 queue.dequeue();

 queue.enqueue(5);

 queue.dequeue();

 queue.enqueue(6);

 queue.enqueue(7);

 queue.dequeue();

 queue.enqueue(8);

 queue.enqueue(9);

 }

}


Question 5:

Implement a program to Search In A Binary Search Tree.

Answer:

import java.util.*;

/*Representing a Node of a binary tree */

class Node{

    int value;

    Node left,right;

    Node(int value)

    {

        this.value=value; 

        left=null;

        right=null;

     }

}

class SearchNode

{

    Node root; //root of a binary search tree

    SearchNode()

    {

        root=null;

     }

    public Node searchNode(Node root,int value)

    {

        if(root==null)

            return null;

        if(root.value==value)   // return true if value is found in binary tree

            return root;

        else if(value <root.value)  

            return searchNode(root.left,value);  //traverse left subtree

        else 

            return searchNode(root.right,value);  //traverse right subtree

    }

     public static void main(String[] args) 

    {

        //Adding Nodes to the binary tree

        SearchNode tree=new SearchNode();

        tree.root=new Node(15);

        tree.root.left=new Node(9);

        tree.root.right=new Node(19);

        tree.root.left.left=new Node(5);

        tree.root.left.right=new Node(13);

        tree.root.right.left=new Node(17);

        tree.root.right.right=new Node(25);

        //calling search function if element is found then it will return true else return false

        Node node=tree.searchNode(tree.root,17);   

        if(node!=null)

            System.out.println(“Element “+node.value+” is found in binary  tree”);

         else 

            System.out.println(“Element is not found in binary tree”);

    }

}


Question 6:

Write the difference between actual and formal parameters?

Answer:


Question 7:

What is Normalization?

Answer:

Normalization is a process of  reorganizing data in a database. Its purpose is to eliminate redundant(repetitive) data and ensure that the data is stored logically.

Well, Normalization is very important as it allows databases to take very small space resulting in increase in performance. It also divides larger tables into smaller tables and links them using relationships.


Question 8:

How does instance differ from schema?

Answer:

Data, for instance, can be changed using addition, deletion, and updation although the schema is the same for the whole database. As the name suggests, instances change frequently whereas the schema does not change frequently. The instance is a collocation of information stored in a database at a particular moment and schema is the overall description of the database.


Question 9:

Give a program on Breadth-First Search (BFS).

Answer:

import java.util.*;

//Representing a Node of a Binary tree

class Node{

    int value;

    Node left,right;

    //constructor

    Node(int value)

    {

        this.value=value;

        left=right=null;

    } 

}

class BreadthFirstSearch

{

    Node root;  //Root of the Binary tree

    BreadthFirstSearch()

   {

       root=null;

   }

    /*level order traversal of a binary tree */  

    public void levelOrder(Node ptr)    

    {

        if(ptr==null)

        return ;

        //Creating a Queue Object

        Queue queue=new LinkedList();

        queue.add(ptr);  //adding an element to queue

        while(!queue.isEmpty())

        {

            Node node=queue.poll();  //removing an element from queue

            System.out.print(node.value+” “);

            if(node.left!=null)

            queue.add(node.left);  //adding an element to queue

            if(node.right!=null)

            queue.add(node.right); //adding an element to queue

        }

    }

   public static void main(String[] args)

    {

        BreadthFirstSearch bst=new BreadthFirstSearch();

        //creating the nodes of binarytree

        bst.root=new Node(50);

        bst.root.left=new Node(30);

        bst.root.right=new Node(70);

        bst.root.left.left=new Node(10);

        bst.root.left.right=new Node(40);

        bst.root.right.left=new Node(60);

        bst.root.right.right=new Node(90);

        bst.levelOrder(bst.root);

 }

}


Question 10:

Calculate the diameter of the Binary Search Tree.

Answer:

import java.util.*;

import java.lang.*;

public class Prepinsta {

public int diameterOfBinaryTree(TreeNode root) {

int[] diameter = new int[1];

height(root, diameter);

return diameter[0];

}

private int height(TreeNode node, int[] diameter) {

if (node == null) {

return 0; }

int lh = height(node.left, diameter);

int rh = height(node.right, diameter);

diameter[0] = Math.max(diameter[0], lh + rh);

return 1 + Math.max(lh, rh);

} }


Question 11:

Write the code to sort an array in the waveform.

Answer:

import java.util.*;

class prepinsta

{

    // A  method to swap two numbers.

    void swap(int arr[], int a, int b)

    {

        int temp = arr[a];

        arr[a] = arr[b];

        arr[b] = temp;

    }

    void sortwave(int arr[], int n)

    {

        // Sort the input array

        Arrays.sort(arr);

        // Swap adjacent elements

        for (int i=0; i<n-1; i += 2)

            swap(arr, i, i+1);

    }

    // Driver method

    public static void main(String args[])

    {

        prepinsta p = new prepinsta();

        int arr[] = {10, 90, 49, 2, 1, 5, 23};

        int n = arr.length;

        p.sortwave(arr, n);

        for (int i : arr)

            System.out.print(i + ” “);

    }

}


Question 12:

What do you mean by ‘pass by value’ and ‘pass by reference’?

Answer:

Pass by Value:

The value of a function parameter is copied to a different location of the memory.

When the variable within the function is accessed or modified, it can only access the copied value, and the original value remains unchanged.

Pass by reference:

The function gets access to the actual variable. The function gets the actual memory address of the variable.


Question 13:

What are entry controlled and exit controlled loops?

Answer:

Entry controlled loops: These loops check the condition at the entry stage and if the condition becomes true, then the control is transferred to the body of the loop.

Example: for loop.

Exit controlled loops: These loops check the condition of exit, and if it is true, then the control breaks and exits from the loop body.

Example:  do while loop


Question 14:

Why is code optimization important?

Answer:

To improve quality and efficiency of codes, code optimization is necessary.  Optimization should increase the speed and performance of the program. Code optimization includes  a smaller size code which consumes less memory and executes more rapidly,  performs fewer input/output operations. Code optimization helps in enhancing the code. By using this technique  we can improve the intermediate code by making it consume fewer resources so that faster-running machine code will result.


Question 15:

Write a code for heap sort.

Answer:

public class Unstop

    //Main() for the execution of the program 

    public static void main(String args[]) 

       { 

          int a[] = {12, 11, 13, 5, 6, 7}; 

          int len = a.length;

           Unstop ob = new Unstop(); 

           ob.sort(a); 

            System.out.println(“Sorted array is”); 

            printArray(a); 

       } 

           public void sort(int a[]) 

               { 

                  int len = a.length; 

                 // Build heap (rearrange array) 

                 for (int i = len / 2 – 1; i >= 0; i–) 

                 heapify(a, len, i); 

                 // One by one extract an element from heap 

                 for (int i=len-1; i>=0; i–) 

                       { 

                         // Move current root to end 

                          int temp = a[0]; 

                          a[0] = a[i]; 

                          a[i] = temp; 

                           // call max heapify on the reduced heap 

                           heapify(a, i, 0); 

                          } 

                  }  

         // To heapify a subtree rooted with node i which is 

        // an index in arr[]. n is size of heap 

       void heapify(int a[], int len, int i) 

           { 

              int largest = i; // Initialize largest as root 

              int l = 2*i + 1; // left = 2*i + 1 

              int r = 2*i + 2; // right = 2*i + 2 

               // If left child is larger than root 

               if (l < len && a[l] > a[largest]) 

               largest = l; 

               // If right child is larger than largest so far 

               if (r < len && a[r] > a[largest]) 

               largest = r; 

               // If largest is not root 

               if (largest != i) 

                     { 

                        int swap = a[i]; 

                        a[i] = a[largest]; 

                        a[largest] = swap; 

                       // Recursively heapify the affected sub-tree 

                         heapify(a, len, largest); 

                       } 

                   } 

           /* A utility function to print array of size n */

           static void printArray(int a[]) 

                 { 

                     int len = a.length; 

                     for (int i=0; i<len; ++i) 

                     System.out.print(a[i]+” “); 

                     System.out.println(); 

                  } 

      }


Question 16:

What is Thrashing in OS?

Answer:

Spending more time on paging than executing of a process is called Thrashing. If there are not enough frames to hold the pages, the process starts swapping pages in and out very frequently to keep executing. Drop in the level of system throughput resulting from frequent swapping of pages is called Thrashing.


Question 17:

Write a code to Delete the nth node in Linked List.

Answer:

import java.lang.*;

// Node Class

class Node {

    int data;

    Node next;

    Node(int x) // parameterized constructor

    {

        data = x;

        next = null;

    }

}

class Main

{

    static Node deleteNthNode(int n, Node head) {

        int len = calcLen(head);

        // Can only insert after 1st position

        // Can’t insert if position to insert is greater than size of Linked List

        if(n < 1 || n > len)

            System.out.println(“Can’t delete\n”);

        else

        {

            if(n == 1)

            {

                // head has to be deleted

                System.out.println(“Deleted: ” + head.data);

                head = head.next;

                return head;

            }

            // required to traverse

            Node temp = head;

            Node previous = null;

            // traverse to the nth node

            while(–n > 0) {

                previous = temp;

                temp = temp.next;

            }

            // assigned next node of the previous node to nth node’s next

            previous.next = temp.next;

            System.out.println(“Deleted: ” + temp.data);

        }

        return head;

    }

    public static Node insert(Node head, int data)

    {

        Node newNode = new Node(data);

        newNode.next = head;

        head = newNode;

        return head;

    }

    static void showList(Node temp) {

        //as linked list will end when Node is Null

        while (temp != null) {

            System.out.print(temp.data + ” “);

            temp = temp.next;

        }

        System.out.println(“\n”);

    }

    static int calcLen(Node node){

        int len = 0;

        while(node!=null)

        {

            node = node.next;

            len++;

        }

        return len;

    }

    public static void main(String args[])

    {

        Node head = null;

        head = insert(head, 35);

        head = insert(head, 34);

        head = insert(head, 33);

        head = insert(head, 32);

        head = insert(head, 31);

        head = insert(head, 30);

        showList(head);

        head = deleteNthNode( 3, head);

        head = deleteNthNode( 4, head);

        showList(head);

    }

}


Question 18:

What is the use of mutex?

Answer:

Mutex means mutual exclusion object. It is used to provide locking in threads. It ensures proper thread synchronization between multiple threads such that only one thread can execute the program at a time.


Question 19:

What is the difference between standard modules and class modules?

Answer:

Only one copy of the data is there in standard modules while in class module there is encapsulates the data within each instance of the class. This is the major difference between standard module and class module. classes can be instantiated as objects while standard modules cannot. In the standard module, you use build-in procedure, properties, method etc.  standard module is for using procedure, properties, method etc to write code.


Question 20:

Write a program for Postfix to Prefix Conversion.

Answer:

import java.util.Stack;

public class PostFixToPreFix {

    static boolean isOperator(char x){

        switch (x){

            case ‘-‘:

            case ‘+’:

            case ‘/’:

            case ‘*’:

            case ‘^’:

                return true;

        }

        return false;

    }

    public static String convert(String exp){

        Stack<String> st = new Stack<>();

        for (int i = 0; i  exp.length() ; i++) {

            char c = exp.charAt(i);

            if(isOperator(c)){

                String s1 = st.pop();

                String s2 = st.pop();

                String temp = c + s2 + s1;

                st.push(temp);

            }else{

                st.push(c+“”);

            }

        }

        String result = st.pop();

        return result;

    }

    public static void main(String[] args) {

        String postfix = “AB+CD-*”;

        System.out.println(“Postfix exp: “ + postfix);

        System.out.println(“Prefix exp: “ + convert(postfix));

    }

}

Amazon Top coding questions in interview

Question 1:

Given an array of N elements, where each element is at most K away from its target position, devise an algorithm that sorts in O(N log K) time

Examples: 

Input: arr[] = {6, 5, 3, 2, 8, 10, 9}, K = 3 

Output: arr[] = {2, 3, 5, 6, 8, 9, 10}

Input: arr[] = {10, 9, 8, 7, 4, 70, 60, 50}, k = 4

Output: arr[] = {4, 7, 8, 9, 10, 50, 60, 70}


Question 2:

Given a binary tree and a leaf node from this tree. It is known that in 1s all nodes connected to a given node (left child, right child, and parent) get burned in 1 second. Then all the nodes which are connected through one intermediate get burned in 2 seconds, and so on. The task is to find the minimum time required to burn the complete binary tree.

Examples: 

 Input : 

            1

       /       \

      2          3

    /  \          \

   4    5          6

      /   \         \

     7     8         9

                      \

                       10

Leaf = 8

Output : 7

Initially 8 is set to fire at 0th sec.

            1

       /       \

      2          3

    /  \          \

   4    5          6

      /   \         \

     7     F         9

                      \

                       10

After 1s: 5 is set to fire.

            1

       /       \

      2          3

    /  \          \

   4    F          6

      /   \         \

     7     F         9

                      \

                       10

After 2s: 2, 7 are set to fire.

            1

       /       \

      F          3

    /  \          \

   4    F          6

      /   \         \

     F     F         9

                      \

                       10

After 3s: 4, 1 are set to fire.

            F

       /       \

      F          3

    /  \          \

   F    F          6

      /   \         \

     F     F         9

                      \

                       10

After 4s: 3 is set to fire.

            F

       /       \

      F          F

    /  \          \

   F    F          6

      /   \         \

     F     F         9

                      \

                       10

After 5s: 6 is set to fire.

            F

       /       \

      F          F

    /  \          \

   F    F          F

      /   \         \

     F     F         9

                      \

                       10

After 6s: 9 is set to fire.

            F

       /       \

      F          F

    /  \          \

   F    F          F

      /   \         \

     F     F         F

                      \

                       10

After 7s: 10 is set to fire.

            F

       /       \

      F          F

    /  \          \

   F    F          F

      /   \         \

     F     F         F

                      \

                       F

It takes 7s to burn the complete tree. 


Question 3:

The task is to find out minimum number of operation required to convert number x into y using only above two operations. We can apply these operations any number of times.

Constraints: 

1 <= x, y <= 1000

Example:  

Input : x = 4, y = 7

Output : 2

We can transform x into y using following

two operations.

  1. 4*2  = 8
  2. 8-1  = 7

Input  : x = 2, y = 5

Output : 4

We can transform x into y using following

four operations.

  1. 2*2  = 4
  2. 4-1   = 3
  3. 3*2  = 6
  4. 6-1   = 5

Answer = 4

Note that other sequences of two operations 

would take more operations.


Question 4:

Reverse a Stack without using recursion and extra space. Even the functional Stack is not allowed.

Examples:  

Input : 1->2->3->4

Output : 4->3->2->1

Input :  6->5->4

Output : 4->5->6


Question 5:

Given a string you need to print the size of the longest possible substring that has exactly K unique characters. If there is no possible substring then print -1.

Example 1:

Input:

S = “aabacbebebe”, K = 3

Output: 

7

Explanation: 

“cbebebe” is the longest substring with 3 distinct characters.


Question 6:

Given a grid of size n*m (n is the number of rows and m is the number of columns in the grid) consisting of ‘0’s (Water) and ‘1’s(Land). Find the number of islands.

Note: An island is either surrounded by water or boundary of grid and is formed by connecting adjacent lands horizontally or vertically or diagonally i.e., in all 8 directions.

Example 1:

Input:

grid = {{0,1},{1,0},{1,1},{1,0}}

Output:

1

Explanation:

The grid is-

0 1

1 0

1 1

1 0

All lands are connected.


Question 7:

Given an integer N, the task is to count all possible strings of length N consisting of vowels {a, e, i, o, u} that can be formed such that each string is sorted in lexicographical order.

Examples:

Input: N = 2

Output: 15

Explanation: The strings of length 2 which are sorted in lexicographical order are [“aa”, “ae”, “ai”, “ao”, “au”, “ee”, “ei”, “eo”, “eu”, “ii”, “io”, “iu”, “oo”, “ou”, “uu”].

Input: N = 1

Output: 5

Explanation: The strings of length 1 which are sorted in lexicographical order are [“a”, “e”, “i”, “o”, “u”].


Question 8:

Given a linked list L of integers, the task is to return a linked list of integers such that it contains next greater element for each element in the given linked list. If there doesn’t any greater element for any element then insert 0 for it.

Examples: 

Input: 2->1->3->0->5 

Output: 3->3->5->5->0

Input: 1->2->3 

Output: 2->3->0 


Question 9:

Given a string S consisting of lowercase Latin Letters, the task is to find the first non-repeating character in S.


Question 10:

Find the difference between the maximum lcm formed by any pairs from an array and the maximum gcd that can be formed by any pairs.


Question 11:

Write a program to find the number of subsets having an average equal to the given average value k.


Question 12:

Write a program to compute the minimum number of question marks required for matching all the strings.


Question 13:

Write a program to compute the cost of merging the given number of Alexa devices where the cost of merging any two devices was equal to sum of diameters of both the Alexa devices.


Question 14:

Write a program to clone a doubly linked list using random pointer.


Question 15:

Given a positive integer K, the task is to find the minimum number of operations of the following two types, required to change 0 to K: 

Add one to the operand

Multiply the operand by 2.

Examples:  

Input: K = 1 

Output: 1 

Explanation: 

Step 1: 0 + 1 = 1 = K

Input: K = 4 

Output: 3 

Explanation: 

Step 1: 0 + 1 = 1, 

Step 2: 1 * 2 = 2, 

Step 3: 2 * 2 = 4 = K 


Question 16:

Devise a sorting algorithm


Question 17:

Given an array arr[] of size N, the task is to count the number of subarrays having an average exactly equal to k.

Examples:

Input: arr[ ] = {1, 4, 2, 6, 10}, N = 6, K = 4

Output: 3

Explanation: The subarrays with an average equal to 4 are {4}, {2, 6}, {4, 2, 6}.

Input: arr[ ] = {12, 5, 3, 10, 4, 8, 10, 12, -6, -1}, N = 10, K = 6

Output: 4


Question 18:

Given a binary array and an integer m, find the position of zeroes flipping which creates maximum number of consecutive 1’s in array.

Examples : 

Input:   arr[] = {1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1}

         m = 2

Output:  5 7

We are allowed to flip maximum 2 zeroes. If we flip

arr[5] and arr[7], we get 8 consecutive 1’s which is

maximum possible under given constraints 


Question 19:

Given a binary circular array of size N, the task is to find the count maximum number of consecutive 1’s present in the circular array.

Examples: 

Input: arr[] = {1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1} 

Output: 6 

The last 4 and first 2 positions have 6 consecutive ones. 

Input: a[] = {0, 1, 0, 1, 0, 1, 0, 1, 0, 1} 

Output: 1


Question 20:

Given an array of words, print all anagrams together. For example, if the given array is {“cat”, “dog”, “tac”, “god”, “act”}, then output may be “cat tac act dog god”.


Question 21:

You are given a LinkedList and you need to find the longest nonincreasing segment (i.e. subarray), you were required to return the segment in the form of LinkedList.


Question 22:

You are given an array and a number X, you need to find the total number of pairs in the array which are divisible by X.


Question 23:

Students’ Position in Row Problem: Given an input of weights of children, find the position of a child such that all students lighter to him are on his left, and the ones heavier than him are on his right. Input: 56 54 63 74 69 Output: 3


Question 24:

You are given a Binary Search Tree (BST) where each node has an integer value. Implement a function or method to transform the given BST into a Greater Sum Tree, following the “Transform BST to Greater Sum Tree” approach.


Question 25:

Given a string str, find the length of the longest substring without repeating characters. 

Example:

Example 1:

Input: “ABCDEFGABEF”

Output: 7

Explanation: The longest substring without repeating characters are “ABCDEFG”, “BCDEFGA”, and “CDEFGAB” with lengths of 7


Question 26:

Given a rectangular matrix which has only two possible values ‘X’ and ‘O’. The values ‘X’ always appear in form of rectangular islands and these islands are always row-wise and column-wise separated by at least one line of ‘O’s. Note that islands can only be diagonally adjacent. Count the number of islands in the given matrix. 

Examples: 

mat[M][N] =  {{‘O’, ‘O’, ‘O’},

              {‘X’, ‘X’, ‘O’},

              {‘X’, ‘X’, ‘O’},

              {‘O’, ‘O’, ‘X’},

              {‘O’, ‘O’, ‘X’},

              {‘X’, ‘X’, ‘O’}

             };

Output: Number of islands is 3

mat[M][N] =  {{‘X’, ‘O’, ‘O’, ‘O’, ‘O’, ‘O’},

              {‘X’, ‘O’, ‘X’, ‘X’, ‘X’, ‘X’},

              {‘O’, ‘O’, ‘O’, ‘O’, ‘O’, ‘O’},

              {‘X’, ‘X’, ‘X’, ‘O’, ‘X’, ‘X’},

              {‘X’, ‘X’, ‘X’, ‘O’, ‘X’, ‘X’},

              {‘O’, ‘O’, ‘O’, ‘O’, ‘X’, ‘X’},

             };

Output: Number of islands is 4


Question 27:

AuxiliaryGiven two sorted linked lists consisting of N and M nodes respectively. The task is to merge both of the lists (in place) and return the head of the merged list.

Examples:

Input: a: 5->10->15, b: 2->3->20

Output: 2->3->5->10->15->20

Input: a: 1->1, b: 2->4

Output: 1->1->2->4


Question 28:

Given a binary tree, print boundary nodes of the binary tree Anti-Clockwise starting from the root.


Question 29:

Given a string str, find the length of the longest substring without repeating characters. 

Example:

Example 1:

Input: “ABCDEFGABEF”

Output: 7

Explanation: The longest substring without repeating characters are “ABCDEFG”, “BCDEFGA”, and “CDEFGAB” with lengths of 7


Question 30:

Given an array and an integer K, find the maximum for each and every contiguous subarray of size K.

Examples : 

Input: arr[] = {1, 2, 3, 1, 4, 5, 2, 3, 6}, K = 3 

Output: 3 3 4 5 5 5 6

Explanation: Maximum of 1, 2, 3 is 3

                       Maximum of 2, 3, 1 is 3

                       Maximum of 3, 1, 4 is 4

                       Maximum of 1, 4, 5 is 5

                       Maximum of 4, 5, 2 is 5 

                       Maximum of 5, 2, 3 is 5

                       Maximum of 2, 3, 6 is 6


Question 31:

Given a binary tree, task is to find subtree with maximum sum in tree.

Examples:  

Input :       1

            /   \

           2      3

          / \    / \

         4   5  6   7

Output: 28

As all the tree elements are positive,

the largest subtree sum is equal to

sum of all tree elements.


Question 32:

Given an array arr[] of positive numbers, The task is to find the maximum sum of a subsequence such that no 2 numbers in the sequence should be adjacent in the array.

Examples: 

Input: arr[] = {5, 5, 10, 100, 10, 5}

Output: 110

Explanation: Pick the subsequence {5, 100, 5}.

The sum is 110 and no two elements are adjacent. This is the highest possible sum.


Question 33:

Given a binary tree with N nodes, in which each node value represents the number of candies present at that node, and there are N candies in total. In one move, one may choose two adjacent nodes and move one candy from one node to another (the move may be from parent to child, or from child to parent.) 

The task is to find the number of moves required such that every node has exactly one candy.

Examples: 

Input :      3

           /   \

          0     0 

Output : 2

Explanation: From the root of the tree, we move one 

candy to its left child, and one candy to

its right child.


Question 34:

The right view of a Binary Tree is a set of nodes visible when the tree is visited from the Right side.

Examples: 

Input:

          1

       /     \

     2        3

   /   \       /  \

  4     5   6    7

                 \

                   8

Output: Right view of the tree is 1 3 7 8


Question 35:

Given an array of integers, find the nearest smaller number for every element such that the smaller element is on the left side.

Input:  arr[] = {1, 6, 4, 10, 2, 5}

Output:         {_, 1, 1,  4, 1, 2}

First element (‘1’) has no element on left side. For 6, 

there is only one smaller element on left side ‘1’. 

For 10, there are three smaller elements on left side (1,

6 and 4), nearest among the three elements is 4.


Question 36:

Given a Binary Tree where each node has positive and negative values. Convert this to a tree where each node contains the sum of the left and right sub trees in the original tree. The values of leaf nodes are changed to 0.

For example, the following tree  

                  10

               /      \

             -2        6

           /   \      /  \ 

         8     -4    7    5

should be changed to 

                 20(4-2+12+6)

               /      \

         4(8-4)      12(7+5)

           /   \      /  \ 

         0      0    0    0


Question 37:

Given an array of N non-negative integers arr[] representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

Examples:  

Input: arr[] = {2, 0, 2}

Output: 2

Explanation: The structure is like below.

We can trap 2 units of water in the middle gap.


Question 38:

Given a sorted dictionary of an alien language having N words and k starting alphabets of standard dictionary. Find the order of characters in the alien language.

Note: Many orders may be possible for a particular test case, thus you may return any valid order and output will be 1 if the order of string returned by the function is correct else 0 denoting incorrect string returned.

Input: 

N = 5, K = 4

dict = {“baa”,”abcd”,”abca”,”cab”,”cad”}

Output:

1

Explanation:

Here order of characters is 

‘b’, ‘d’, ‘a’, ‘c’ Note that words are sorted 

and in the given language “baa” comes before 

“abcd”, therefore ‘b’ is before ‘a’ in output.

Similarly we can find other orders.


Question 39:

Given an array of positive integers, replace each element in the array such that the difference between adjacent elements in the array is less than or equal to a given target. We need to minimize the adjustment cost, that is the sum of differences between new and old values. We basically need to minimize ?|A[i] – Anew[i]| where 0 ? i ? n-1, n is size of A[] and Anew[] is the array with adjacent difference less than or equal to the target. Assume all elements of the array is less than constant M = 100.

Examples: 

Input: arr = [1, 3, 0, 3], target = 1

Output: Minimum adjustment cost is 3

Explanation: One of the possible solutions 

is [2, 3, 2, 3]

Input: arr = [2, 3, 2, 3], target = 1

Output: Minimum adjustment cost is 0

Explanation:  All adjacent elements in the input 

array are already less than equal to given target


Question 40:

Given two values n1 and n2 in a Binary Search Tree, find the Lowest Common Ancestor (LCA). You may assume that both values exist in the tree. 

Leave a Comment

    🚀 Join Common Jobs Pro — Referrals & Profile Visibility Join Now ×
    🔥