
Amazon


30+ Amazon SDE-2 Interview Questions and Answers
Q1. Ways To Make Coin Change
Given an infinite supply of coins of varying denominations, determine the total number of ways to make change for a specified value using these coins. If it's not possible to make the c...read more
The task is to find the total number of ways to make change for a specified value using given denominations.
Use dynamic programming to solve this problem efficiently.
Create a 2D array to store the number of ways to make change for each value using different denominations.
Iterate through each denomination and update the array based on the number of ways to make change for each value.
Return the value at the last cell of the array as the final result.
Q2. Shopping Options Problem Statement
Given arrays representing the costs of pants, shirts, shoes, and skirts, and a budget amount 'X', determine the total number of valid combinations that can be purchased such t...read more
Determine total number of valid shopping combinations within budget
Iterate through all possible combinations of items from each array
Check if the total cost of the combination is within the budget
Return the count of valid combinations
Q3. There is a 12 km road and a contractor who is in-charge of repairing it. Contractor updates you about the work which is done in patches. Like “Road between 3.2 km to 7.9 km repaired ”, “Road between 1.21 km to...
read moreFind longest continuous patch on a 12 km road with updates in patches
Maintain a variable to keep track of current patch length
Update the variable whenever a new patch is added
Maintain a variable to keep track of longest patch so far
Compare current patch length with longest patch length and update if necessary
Use a sorted data structure like a binary search tree to store the patches for efficient search
Time complexity: O(nlogn) where n is the number of updates by the contracto...read more
Q4. Reverse Linked List Problem Statement
Given a Singly Linked List of integers, your task is to reverse the Linked List by altering the links between the nodes.
Input:
The first line of input is an integer T, rep...read more
Reverse a singly linked list by altering the links between nodes.
Iterate through the linked list and reverse the links between nodes
Use three pointers to keep track of the current, previous, and next nodes
Update the links between nodes to reverse the list
Return the head of the reversed linked list
Q5. Validate Binary Search Tree Problem Statement
Given a binary tree with 'N' nodes, determine if it is a Binary Search Tree (BST). Return true
if the tree is a BST, otherwise return false
.
Example:
Input:
1 2 3 4...read more
Validate if a given binary tree is a Binary Search Tree (BST) or not.
Check if the left subtree of a node contains only nodes with values less than the node's value.
Check if the right subtree of a node contains only nodes with values greater than the node's value.
Ensure that both the left and right subtrees are also binary search trees.
Traverse the tree in-order and check if the elements are in sorted order.
Use a recursive function to validate each node's value against its sub...read more
Q6. Max Submatrix Problem Statement
You are provided with a matrix MAT
consisting of integers, with dimensions N x M
(i.e., N rows and M columns). Your objective is to determine the maximum sum submatrix within thi...read more
Find the maximum sum submatrix in a given matrix.
Iterate over all possible submatrices and calculate their sums
Use Kadane's algorithm to find the maximum sum subarray in each row
Combine the sums of rows to find the maximum sum submatrix
Q7. Median in a Stream Problem Statement
Your task is to determine the median of integers as they are read from a data stream. The median is the middle value in the ordered list of numbers. If the list length is ev...read more
Find median of integers in a data stream as they are read.
Use two heaps - max heap for lower half of numbers and min heap for upper half.
Keep the size of two heaps balanced to find the median efficiently.
Handle even and odd number of elements separately to calculate median.
Return vector of medians after each element is read from the stream.
Q8. Flatten Multi-Level Linked List
You are given a multi-level linked list containing 'N' nodes. Each node has 'next' and 'child' pointers that may or may not point to other nodes. Your task is to flatten this mul...read more
Flatten a multi-level linked list into a single linked list by rearranging the pointers.
Traverse the linked list and whenever a node has a child, flatten the child list and append it after the current node.
Update the 'next' and 'child' pointers accordingly while flattening the list.
Continue this process until all nodes are rearranged into a single linked list.
Q9. Word Break Problem Statement
You are given a non-empty string without spaces, referred to as 'sentence', and a list of non-empty strings representing a dictionary. Your task is to construct and return all possi...read more
Given a sentence and a dictionary, construct and return all possible sentences by inserting spaces to form words from the dictionary.
Use backtracking to generate all possible combinations of words from the dictionary to form sentences.
Check if a substring of the sentence matches any word in the dictionary, if so, recursively call the function with the remaining substring.
Continue this process until the entire sentence is segmented into words from the dictionary.
Return all val...read more
Q10. Binary Tree Conversion to Greater Tree
Given a binary tree with 'N' nodes, transform it into a Greater Tree. In this transformation, each node's value should be updated to the sum of its original value and the ...read more
Convert a binary tree into a Greater Tree by updating each node's value to the sum of its original value and the values of all nodes greater than or equal to it.
Traverse the tree in reverse inorder (right, root, left) to update the nodes' values.
Keep track of the sum of nodes visited so far to update each node's value.
Recursively update the node's value by adding the sum of greater nodes to it.
Q11. Check for Valid Parentheses
You are given a string STR
containing only the characters "{", "}", "(", ")", "[", and "]". Your task is to determine if the parentheses in the string are balanced.
Input:
The first ...read more
Check if the given string containing only parentheses is balanced or not.
Use a stack to keep track of opening parentheses.
Iterate through the string and push opening parentheses onto the stack.
When a closing parenthesis is encountered, pop from the stack and check if it matches the corresponding opening parenthesis.
If at the end the stack is empty, return 'YES' else return 'NO'.
Q12. The Ninja Port Problem
Ninja is in a city with 'N' colonies, where each colony contains 'K' houses. He starts at house number "sourceHouse" in colony number "sourceColony" and wants to reach house number "desti...read more
The Ninja Port Problem involves finding the minimum time for a ninja to travel between colonies and houses using secret paths and teleportation.
Calculate the minimum time considering teleportation within colonies, traveling between colonies, and secret paths.
Keep track of the number of secret paths used and ensure they are one-way.
Consider the constraints provided to optimize the solution.
Example: N=2, K=3, S=1, P=1, sourceHouse=1, sourceColony=1, destinationHouse=3, destinat...read more
Q13. Clone a Binary Tree with Random Pointers
Given a binary tree where each node has pointers to its left, right, and a random node, create a deep copy of the binary tree.
Input:
The first line contains an integer ...read more
Clone a binary tree with random pointers and verify if cloning was successful by printing inorder traversal.
Create a deep copy of the binary tree with random pointers.
Print the inorder traversal of the cloned binary tree.
Verify cloning success by printing '1' if successful, '0' otherwise.
Q14. Group Anagrams Together
Given an array/list of strings STR_LIST
, group the anagrams together and return each group as a list of strings. Each group must contain strings that are anagrams of each other.
Example:...read more
Group anagrams together in a list of strings.
Iterate through the list of strings and sort each string to group anagrams together.
Use a hashmap to store the sorted string as key and the original string as value.
Return the values of the hashmap as the grouped anagrams.
Q15. Add Two Numbers Represented by Linked Lists
Your task is to find the sum list of two numbers represented by linked lists and return the head of the sum list.
Explanation:
The sum list should be a linked list re...read more
Add two numbers represented by linked lists and return the head of the sum list.
Traverse both linked lists simultaneously while keeping track of carry from previous sum
Create a new linked list to store the sum of the two numbers
Handle cases where one linked list is longer than the other by padding with zeros
Update the sum and carry values accordingly while iterating through the linked lists
Q16. Course Schedule II Problem Statement
You are provided with a number of courses 'N', some of which have prerequisites. There is a matrix named 'PREREQUISITES' of size 'M' x 2. This matrix indicates that for ever...read more
Given courses with prerequisites, determine a valid order to complete all courses.
Create a graph with courses as nodes and prerequisites as edges.
Use topological sorting to find a valid order to complete all courses.
Return an empty list if it's impossible to complete all courses.
Q17. Implementing a Priority Queue Using Heap
Ninja has been tasked with implementing a priority queue using a heap data structure. However, he is currently busy preparing for a tournament and has requested your ass...read more
Implement a priority queue using a heap data structure with push, pop, getMaxElement, and isEmpty functions.
Implement a priority queue using a max heap data structure.
Use the provided class structure and complete the push, pop, getMaxElement, and isEmpty functions.
For push operation, insert the element into the heap and maintain the heap property.
For pop operation, remove the largest element from the heap.
For getMaxElement operation, return the largest element from the heap.
F...read more
Q18. Ninja and the Bulbs Challenge
Ninja owns an electronic shop and possesses 'N' bulbs. To verify the quality of the bulbs, Ninja performs a unique technique. After 'N' rounds of this process, bulbs that remain on...read more
Determine the number of good quality bulbs remaining after 'N' rounds of a unique technique.
Start with all bulbs on in the first round
Toggle every 'i' bulb in 'i' round
Count the bulbs that remain on after 'N' rounds
Q19. Maximize the Sum Through Two Arrays
You are given two sorted arrays of distinct integers, ARR1
and ARR2
. If there is a common element in both arrays, you can switch from one array to the other.
Your task is to ...read more
Find the maximum sum by traversing through common elements in two sorted arrays.
Start with the array containing the smaller first common element
Switch arrays at common elements to maximize the sum
Continue adding elements until the end of the arrays
Q20. Validate Binary Search Tree (BST)
You are given a binary tree with 'N' integer nodes. Your task is to determine whether this binary tree is a Binary Search Tree (BST).
BST Definition:
A Binary Search Tree (BST)...read more
Validate if a given binary tree is a Binary Search Tree (BST) or not.
Check if the left subtree of a node contains only nodes with data less than the node's data
Check if the right subtree of a node contains only nodes with data greater than the node's data
Recursively check if both left and right subtrees are also binary search trees
Q21. Boundary Traversal of Binary Tree Problem Statement
You are given a binary tree of integers. Your task is to print the boundary nodes of this binary tree in an anti-clockwise direction starting from the root no...read more
Print the boundary nodes of a binary tree in an anti-clockwise direction starting from the root node.
Traverse the left boundary nodes from top to bottom
Traverse the leaf nodes from left to right
Traverse the right boundary nodes from bottom to top
Handle cases where nodes are null (-1)
Print the boundary nodes in the specified order
Q22. Rain Water Trapping Problem Statement
Given an array/list ARR
of size N
, representing an elevation map where each element ARR[i]
denotes the elevation of the i-th
bar. Your task is to calculate and print the to...read more
Calculate the total amount of rainwater that can be trapped between given elevations in an elevation map.
Use two-pointer approach to keep track of left and right boundaries.
Calculate the trapped water by finding the minimum of left_max and right_max for each bar.
Subtract the current bar's height from the minimum of left_max and right_max to get the trapped water.
Keep updating the left_max and right_max as you iterate through the array.
Q23. Number of Islands Problem Statement
You are provided with a 2D array or list containing 'N' rows and 'M' columns, filled with 1s and 0s. Here, 1 indicates land, and 0 indicates water.
Your task is to identify a...read more
Count the number of islands in a 2D matrix filled with 1s and 0s.
Iterate through the matrix and perform depth-first search (DFS) to find connected islands.
Use a visited array to keep track of visited cells to avoid redundant calculations.
Increment the island count whenever a new island is encountered.
Consider all eight directions (horizontal, vertical, and diagonal) while exploring the island.
Handle edge cases like out of bounds and already visited cells.
Q24. Next Greater Element Problem Statement
You are given an array arr
of length N
. For each element in the array, find the next greater element (NGE) that appears to the right. If there is no such greater element, ...read more
The task is to find the next greater element for each element in an array to its right, if no greater element exists, return -1.
Use a stack to keep track of elements for which the next greater element is not found yet.
Iterate through the array from right to left, popping elements from the stack until a greater element is found.
Store the next greater element for each element in a separate array.
If the stack is empty after iterating through the array, it means no greater elemen...read more
Q25. Valid Parenthesis Problem Statement
Given a string str
composed solely of the characters "{", "}", "(", ")", "[", and "]", determine whether the parentheses are balanced.
Input:
The first line contains an integ...read more
Check if given string of parentheses is balanced or not.
Use a stack to keep track of opening parentheses and pop when a closing parenthesis is encountered.
If stack is empty at the end and all parentheses are matched, the string is balanced.
If stack is not empty at the end or mismatched parentheses are encountered, the string is not balanced.
Q26. Bottom View of Binary Tree Problem Statement
Given a binary tree, the task is to print its bottom view from left to right. Assume the left and the right child nodes make a 45-degree angle with their parent node...read more
The task is to print the bottom view of a binary tree from left to right.
Traverse the binary tree in level order and keep track of the horizontal distance of each node from the root.
For each horizontal distance, update the node value in a map to get the bottom view nodes.
Print the values of the map in sorted order of horizontal distance to get the bottom view sequence.
Q27. Distance Between Two Nodes in a Binary Tree
Given a binary tree and the values of two distinct nodes, determine the distance between these two nodes in the tree. The distance is defined as the minimum number of...read more
Calculate the distance between two nodes in a binary tree.
Traverse the tree to find the paths from the root to each node
Find the lowest common ancestor of the two nodes
Calculate the distance by summing the distances from each node to the common ancestor
Q28. Balanced Parentheses Combinations
Given an integer N
representing the number of pairs of parentheses, find all the possible combinations of balanced parentheses using the given number of pairs.
Explanation:
Con...read more
Generate all possible combinations of balanced parentheses for a given number of pairs.
Use recursion to generate all possible combinations of balanced parentheses.
Keep track of the number of open and close parentheses used in each combination.
Terminate recursion when the number of open and close parentheses used equals the given number of pairs.
Q29. Add First and Second Half Problem Statement
You are provided with a Singly Linked List having 'N' nodes, where each node contains a single digit.
Your task is to return a node 'X', which serves as the head of a...read more
Return a node representing the head of a new Linked List with the sum of the 1st and 2nd half of the given Linked List.
Split the Linked List into two halves
Reverse the 2nd half of the Linked List
Add the corresponding digits from both halves while considering carry
Create a new Linked List with the sum digits
Q30. Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them. For example : ABC -> A BC, AB C, ABC, A B C
Given a string, print all possible strings that can be made by placing spaces (zero or one) in between them.
Use recursion to generate all possible combinations of spaces
For each recursive call, either add a space or don't add a space between the current character and the next character
Base case is when there are no more characters left to add spaces between
Time complexity is O(2^n) where n is the length of the string
Yes, I can design a parking lot using LLD and a tiny URL service using HLD.
For designing a parking lot using LLD, we can create classes like ParkingLot, ParkingSpot, Vehicle, etc. with their respective attributes and methods.
For designing a tiny URL service using HLD, we can focus on scalability, fault tolerance, and performance. We can use techniques like sharding, caching, load balancing, etc.
In the parking lot LLD, we can consider functionalities like assigning spots, chec...read more
Q32. Design data structure that supports insert(), remove(), find-max(), delete-max() operations. All operations should run in O(1) time. Lots of discussion was there, discussed many approaches.
Design a data structure with O(1) insert, remove, find-max, and delete-max operations.
Use a doubly linked list to maintain the elements in sorted order.
Use a hash table to store the pointers to the nodes in the linked list.
Maintain a pointer to the maximum element in the hash table.
Update the pointers in the hash table when inserting or removing elements.
Update the maximum pointer when deleting or inserting the maximum element.
Q33. A stream of characters is coming, at any moment you have to tell ‘k’ elements closest to a given number (code)
Find 'k' elements closest to a given number from a stream of characters.
Use a priority queue to keep track of closest elements.
Update the queue as new characters come in.
Return the 'k' closest elements from the queue.
Q34. Find sum of all numbers that are formed from root to leaf path (code) expected time complexity O(n)
Find sum of all numbers formed from root to leaf path in a binary tree
Traverse the binary tree using DFS
At each leaf node, add the number formed from root to leaf path to a sum variable
Return the sum variable
Time complexity: O(n)
Example: For a binary tree with root value 1, left child 2 and right child 3, the sum would be 12 + 13 = 25
Q35. Check whether given link list represents palindrome
Check if a given linked list is a palindrome.
Traverse the linked list and store the values in an array.
Compare the first and last elements of the array, then move towards the center.
If all elements match, the linked list is a palindrome.
Alternatively, use two pointers to find the middle of the linked list and reverse the second half.
Compare the first half with the reversed second half to check for a palindrome.
Design a local transport system similar to BMTC
Introduce a fleet of buses covering various routes within the city
Implement a smart card system for easy payment and tracking
Include different types of buses like regular, AC, and Volvo for passenger comfort
Have designated bus stops with real-time information on bus arrivals
Offer discounted fares for students and senior citizens
Q37. Find median of an unsorted array. (code
Find median of an unsorted array.
Sort the array and find the middle element
Use quickselect algorithm to find the median in O(n) time
If the array is small, use brute force to find the median
Q38. Preorder traversal without using recursion
Preorder traversal without recursion
Use a stack to keep track of nodes
Push right child first and then left child onto stack
Pop top of stack and print value
Repeat until stack is empty
Design a live video broadcast platform.
Implement video streaming functionality using protocols like RTMP or WebRTC
Include features for live chat, reactions, and audience engagement
Ensure scalability and reliability by using cloud services like AWS or Azure
Provide analytics for viewership data and user engagement
Integrate monetization options such as ads or subscriptions
More about working at Amazon










Interview Process at Amazon SDE-2

Top SDE-2 Interview Questions from Similar Companies






Reviews
Interviews
Salaries
Users/Month

