
Amazon


60+ Amazon Software Engineer Interview Questions and Answers
Q1. Reverse a Singly Linked List
Given a singly linked list of integers, your task is to return the head of the reversed linked list.
Explanation:
Reverse a given singly linked list so that the last element becomes...read more
Reverse a singly linked list of integers.
Iterate through the linked list and reverse the pointers to point to the previous node instead of the next node.
Keep track of the current, previous, and next nodes while traversing the list.
Update the head of the linked list to be the last node encountered during traversal.
Q2. Sum Between Zeroes Problem Statement
Given a singly linked list containing a series of integers separated by the integer '0', modify the list by merging nodes between two '0's into a single node. This merged no...read more
Merge nodes between zeroes in a linked list to store the sum of included nodes.
Traverse the linked list and keep track of sum between zeroes
Merge nodes between zeroes by updating the sum in the merged node
Handle edge cases like empty list or single node between zeroes
Ensure the list starts and ends with a zero
Q3. Reverse Linked List Problem Statement
Given a singly linked list of integers, your task is to return the head of the reversed linked list.
Example:
Input:
The given linked list is 1 -> 2 -> 3 -> 4 -> NULL.
Outp...read more
Reverse a singly linked list of integers and return the head of the reversed linked list.
Traverse the linked list and reverse the pointers to point to the previous node instead of the next node
Use three pointers - prev, current, and next to reverse the linked list
Update the head of the reversed linked list to be the last element of the original linked list
Example: Input: 1 -> 2 -> 3 -> 4 -> NULL, Output: 4 -> 3 -> 2 -> 1 -> NULL
Q4. Longest Common Subsequence Problem Statement
Given two strings, S
and T
with respective lengths M
and N
, your task is to determine the length of their longest common subsequence.
A subsequence is a sequence tha...read more
The task is to find the length of the longest common subsequence between two given strings.
Use dynamic programming to solve this problem efficiently.
Create a 2D array to store the lengths of common subsequences of substrings.
Iterate through the strings to fill the array and find the longest common subsequence.
Example: For strings 'abcde' and 'ace', the longest common subsequence is 'ace' with a length of 3.
Q5. Minimum Cost to Buy Oranges Problem Statement
You are given a bag of capacity 'W' kg and a list 'cost' of costs for packets of oranges with different weights. Each element at the i-th position in the list indic...read more
Find the minimum cost to purchase a specific weight of oranges given the cost of different weight packets.
Iterate through the list of costs and find the minimum cost to achieve the desired weight
Keep track of the total cost while considering available packet weights
Return -1 if it is not possible to buy exactly the desired weight
Q6. Connecting Ropes with Minimum Cost
You are given 'N' ropes, each of varying lengths. The task is to connect all ropes into one single rope. The cost of connecting two ropes is the sum of their lengths. Your obj...read more
Given 'N' ropes of varying lengths, find the minimum cost to connect all ropes into one single rope.
Sort the lengths of ropes in ascending order.
Keep connecting the two shortest ropes at each step.
Add the cost of connecting the two ropes to the total cost.
Repeat until all ropes are connected.
Return the total cost as the minimum cost to connect all ropes.
Q7. You have given 10 files and you have given a string suggest data structure which ll facilitate efficient search of string in the file if string appears more than ones in that case u have to print line number an...
read moreSuggest a data structure for efficient search of a string in 10 files and print line number and file if string appears more than once.
Use a hash table to store the file name and line number of each occurrence of the string.
Iterate through each file and for each line, check if the string is present and update the hash table accordingly.
Print the hash table entries for the string.
Q8. Given a binary tree in which the node structure has an additional field called “next” which of pointer to tree node type, fill up this field of each node to point to the next node at the same level (NULL if las...
read moreThe task is to fill the 'next' field of each node in a binary tree to point to the next node at the same level.
Use a level order traversal to process the tree nodes.
Maintain a queue to store the nodes at each level.
For each node, set its 'next' field to the next node in the queue.
If a node is the last node at its level, set its 'next' field to NULL.
Q9. Explain the difference between ArrayList and LinkedList in Java. ArrayList is implemented as a dynamic array, while LinkedList is a doubly linked list. ArrayList provides fast random access (O(1) complexity) bu...
read moreArrayList is preferred for frequent retrieval operations due to fast random access, while LinkedList is suitable for frequent insertions/deletions with fast O(1) complexity.
Use ArrayList for scenarios where frequent retrieval operations are needed, such as searching for elements in a large collection.
Choose LinkedList when frequent insertions/deletions are required, like maintaining a queue or stack with dynamic size.
Consider memory overhead and performance trade-offs when de...read more
Q10. there is an infinite stair case and there are n rounds. in i'th round we can jump i steps at one or discard them. it is given that k'th step is broken , find the max height we can reach with out stepping on the...
read moreGiven an infinite staircase with a broken kth step, find the maximum height we can reach in n rounds of jumping i steps.
We can start by jumping the maximum number of steps in each round until we reach the broken step.
After reaching the broken step, we can discard the i steps that would land us on the broken step and jump the remaining steps.
We can continue this pattern until we reach the maximum height we can reach without stepping on the broken step.
Q11. What are the advantages and disadvantages of using Java’s synchronized keyword for thread synchronization? The synchronized keyword ensures that only one thread can access a block of code at a time. It prevents...
read moreReentrantLock should be used instead of synchronized when more flexibility and control over locking mechanisms is required.
Use ReentrantLock when you need to implement advanced locking mechanisms like tryLock() or lockInterruptibly()
ReentrantLock supports fair locking, ensuring that threads acquire the lock in the order they requested it
Explicit unlocking in ReentrantLock can help prevent deadlocks and improve performance in certain scenarios
Q12. What is the difference between == and .equals() in Java? == checks for reference equality, meaning it compares memory addresses. equals() checks for value equality, which can be overridden in user-defined class...
read moreIn Java, == checks for reference equality while equals() checks for value equality. Misuse of == can lead to logical errors.
Override equals() when you want to compare the actual content of objects in user-defined classes.
Override hashCode() method alongside equals() to ensure consistent behavior in collections like HashMap.
Implement Comparable interface and override compareTo() method for natural ordering of objects.
Q13. How does the Java garbage collector work? Garbage collection in Java automatically reclaims memory occupied by unused objects. The JVM has different types of GC algorithms, including Serial, Parallel, CMS, and...
read moreGarbage collection in Java automatically reclaims memory occupied by unused objects using different GC algorithms and memory regions.
Force garbage collection in Java can be done using System.gc() or Runtime.gc() methods.
It is generally not recommended to force garbage collection as it can disrupt the JVM's natural memory management process and cause performance issues.
Forcing garbage collection may not guarantee immediate memory reclamation and can lead to inefficient memory ...read more
Q14. What are the main features of Java 8? Java 8 introduced lambda expressions, enabling functional-style programming. The Stream API allows efficient data processing with map, filter, and reduce operations. Defaul...
read moreLambda expressions in Java 8 improve readability and maintainability by enabling concise and functional-style programming.
Lambda expressions allow writing more compact code by reducing boilerplate code.
They enable passing behavior as arguments to methods, making code more modular and flexible.
Example: (a, b) -> a + b is a lambda expression that adds two numbers.
Q15. You have a dictionary of words. Given a word, print all anagram are in dictionary . State the data structure to be used to solve this problem
To find anagrams of a given word in a dictionary, use a hash table to store sorted versions of each word as keys and their corresponding original words as values.
Create a hash table to store the anagrams
Iterate through each word in the dictionary
Sort the characters of the word and use it as a key in the hash table
If the key already exists, add the word to the list of values for that key
Print the list of values for the given word's sorted characters
Q16. find the nearest greater value of a given value in a BST
Find the nearest greater value of a given value in a Binary Search Tree (BST).
Start from the root node and compare the given value with the current node's value.
If the given value is less than the current node's value, move to the left subtree.
If the given value is greater than the current node's value, move to the right subtree.
Keep track of the closest greater value encountered while traversing the tree.
Return the closest greater value found.
Q17. Explain the difference between ArrayList and LinkedList in Java. When would you choose one over the other?
ArrayList and LinkedList are both classes in Java that implement the List interface, but they have different underlying data structures.
ArrayList uses a dynamic array to store elements, providing fast random access but slower insertion and deletion.
LinkedList uses a doubly linked list to store elements, providing fast insertion and deletion but slower random access.
Choose ArrayList when you need fast random access and know the size of the list beforehand. Choose LinkedList wh...read more
Q18. What is a Java Stream, and how does it differ from an Iterator? Explain how Streams can be used to process collections efficiently.
Java Stream is a sequence of elements that supports functional-style operations. It differs from Iterator by being more declarative and allowing for parallel processing.
Java Stream is a high-level abstraction over collections that allows for functional-style operations like map, filter, reduce, etc.
Streams are more declarative compared to Iterators, which are imperative. This means that with Streams, you specify what you want to do rather than how to do it.
Streams can be used...read more
Q19. Explain the concept of immutability in Java. How does the String class achieve immutability, and what are the advantages of immutable objects?
Immutability in Java means objects cannot be modified after creation. String class achieves immutability by not allowing changes to its value.
Immutability means once an object is created, its state cannot be changed.
String class in Java is immutable because its value cannot be modified once it is assigned.
Advantages of immutable objects include thread safety, security, and ease of caching.
Q20. What is the difference between final, finally, and finalize in Java? Provide examples to illustrate their usage.
final, finally, and finalize have different meanings in Java.
final is a keyword used to restrict the user from changing the value of a variable, making it a constant.
finally is a block of code that is always executed, whether an exception is thrown or not.
finalize is a method used for cleanup operations before an object is garbage collected.
Q21. Explain the Singleton design pattern in Java. How can you implement it safely to ensure thread safety?
Singleton design pattern ensures a class has only one instance and provides a global point of access to it.
Create a private static instance of the class within the class itself.
Provide a public static method to access the instance, creating it if necessary.
Make the constructor private to prevent instantiation from outside the class.
Use synchronized keyword or double-checked locking to ensure thread safety.
Q22. Can you explain the difference between method overloading and method overriding in Java? Provide examples where each should be used.
Method overloading is when multiple methods have the same name but different parameters, while method overriding is when a subclass provides a specific implementation of a method in its superclass.
Method overloading is achieved within the same class by having multiple methods with the same name but different parameters.
Method overriding occurs in a subclass that provides a specific implementation of a method that is already provided by its superclass.
Method overloading is use...read more
Q23. What are Java annotations, and how are they used in frameworks like Spring? Explain the difference between built-in and custom annotations.
Java annotations are metadata that provide data about a program but do not affect the program itself. They are used in frameworks like Spring to configure and customize behavior.
Java annotations are used to provide metadata about classes, methods, fields, etc. in a program.
In frameworks like Spring, annotations are used to configure various aspects of the application, such as dependency injection, transaction management, and request mapping.
Built-in annotations in Java includ...read more
Q24. What are the advantages and disadvantages of using Java’s synchronized keyword for thread synchronization? Can you explain how the ReentrantLock compares to synchronized?
Using Java's synchronized keyword for thread synchronization has advantages like simplicity and disadvantages like potential for deadlock. ReentrantLock offers more flexibility and control.
Advantages of synchronized keyword: simplicity, built-in support in Java
Disadvantages of synchronized keyword: potential for deadlock, lack of flexibility
ReentrantLock advantages: more flexibility, ability to try and lock with timeout
ReentrantLock disadvantages: more verbose syntax, need to...read more
Q25. How does the Java garbage collector work? Can you describe the different types of garbage collection algorithms available in Java?
Java garbage collector manages memory by automatically deallocating memory that is no longer in use.
Java garbage collector runs in the background and identifies objects that are no longer reachable by the application.
It uses different algorithms like Mark-Sweep, Mark-Compact, and Copying to reclaim memory.
Mark-Sweep algorithm identifies and marks objects for deletion, then sweeps through and deallocates them.
Mark-Compact algorithm moves reachable objects to one end of the mem...read more
Q26. What is the Java Memory Model, and how does it affect multithreading and synchronization? How does volatile help ensure memory visibility?
The Java Memory Model defines how threads interact through memory and how synchronization ensures visibility and consistency.
Java Memory Model specifies how threads interact with memory
Synchronization ensures visibility and consistency of shared data among threads
Volatile keyword ensures changes made by one thread are immediately visible to other threads
Example: Using volatile keyword to share a boolean flag among multiple threads
Q27. How do Java Streams handle parallel processing? What are the potential pitfalls of using parallel streams, and how can they be mitigated?
Java Streams can handle parallel processing using parallel streams. Pitfalls include increased complexity and potential for race conditions.
Java Streams can be processed in parallel by calling the parallel() method on a stream.
Potential pitfalls of using parallel streams include increased complexity, potential for race conditions, and performance overhead due to thread management.
To mitigate these pitfalls, ensure that the operations performed on the stream are stateless and ...read more
Q28. What is the difference between == and .equals() in Java? When should each be used, and what issues can arise from improper usage?
In Java, == compares memory addresses while .equals() compares the actual values of objects.
Use == to compare primitive data types or to check if two objects reference the same memory location.
Use .equals() to compare the actual values of objects, especially for String comparisons.
Improper usage can lead to unexpected results, such as comparing objects instead of their values.
Q29. What are the main features of Java 8? Can you explain how lambdas and the Stream API have changed the way Java applications are written?
Java 8 introduced features like lambdas and Stream API which have revolutionized the way Java applications are written.
Lambdas allow for more concise and readable code by enabling functional programming style.
Stream API provides a way to process collections of objects in a functional way, allowing for easier parallel processing and improved performance.
Java 8 also introduced default methods in interfaces, allowing for backward compatibility with existing code.
The new Date and...read more
Q30. What are functional interfaces in Java? How do they work with lambda expressions? Provide an example of a custom functional interface.
Functional interfaces in Java are interfaces with a single abstract method. They can be used with lambda expressions for functional programming.
Functional interfaces have only one abstract method, but can have multiple default or static methods.
Lambda expressions can be used to implement the abstract method of a functional interface concisely.
An example of a custom functional interface is 'Calculator' with a single abstract method 'calculate'.
Q31. Describe the differences between checked and unchecked exceptions in Java. Provide examples and explain how to handle them properly.
Checked exceptions must be handled at compile time, while unchecked exceptions do not need to be caught or declared.
Checked exceptions are subclasses of Exception class, while unchecked exceptions are subclasses of RuntimeException class.
Checked exceptions must be caught or declared in the method signature using 'throws', while unchecked exceptions do not have this requirement.
Examples of checked exceptions include IOException and ClassNotFoundException, while examples of unc...read more
ACID properties in DBMS ensure data integrity and consistency in transactions.
Atomicity: All operations in a transaction are completed successfully or none at all.
Consistency: Data remains consistent before and after the transaction.
Isolation: Transactions are isolated from each other until they are completed.
Durability: Once a transaction is committed, changes are permanent and survive system failures.
Q33. Given a string of parenthesis, write a function if it is balanced
Function to check if a string of parenthesis is balanced
Use a stack to keep track of opening parenthesis
If a closing parenthesis is encountered, pop from stack and check if it matches
If stack is empty and a closing parenthesis is encountered, return False
If all parenthesis are matched and stack is empty, return True
Q34. Find the number of occurrences of words in a paragraph
Count the occurrences of words in a paragraph.
Split the paragraph into words using whitespace as a delimiter.
Create a dictionary to store the count of each word.
Iterate through the words and increment the count in the dictionary.
Return the dictionary with the word counts.
Q35. Find common elements out of two sorted array?
Find common elements out of two sorted array
Use two pointers to traverse both arrays simultaneously
Compare elements at each pointer and move the pointer of the smaller element
If elements are equal, add to common elements list and move both pointers
Stop when either pointer reaches end of array
Q36. In an array where all elements are repeated twice, find an element that is repeated once
Find the element that is repeated once in an array where all elements are repeated twice
Iterate through the array and use a hashmap to keep track of the count of each element
Once the iteration is complete, check the hashmap for the element with a count of 1
Q37. Given a csv file with users and the websites they visited, find the top k most visited website patterns by users
Use a combination of sliding window and hashmap to find top k most visited website patterns by users
Parse the csv file to extract user and website data
Use a sliding window to generate all possible website patterns for each user
Use a hashmap to count the frequency of each website pattern
Sort the website patterns based on frequency and return the top k patterns
Q38. boundary traversal of a tree
Boundary traversal of a tree is the process of visiting the nodes on the boundary of a tree in a specific order.
The boundary traversal can be done in three steps: left boundary, leaf nodes, and right boundary.
For the left boundary, start from the root and traverse down the left side of the tree until reaching a leaf node.
For the leaf nodes, perform an inorder traversal to visit all the leaf nodes of the tree.
For the right boundary, start from the rightmost leaf node and trave...read more
Q39. Convert BST to a Doubly linked list?
Convert a Binary Search Tree to a Doubly Linked List.
Create a DLL node class with left, right, and data fields.
Traverse the BST in-order and add each node to the DLL.
Adjust the left and right pointers of each node to create the DLL.
Return the head of the DLL.
Q40. Cant say because of NDA, make a package dependency ood.
Create a package dependency diagram based on object-oriented design principles.
Identify the main classes/modules in the system
Determine the relationships between classes/modules (e.g. inheritance, composition, aggregation)
Visualize the dependencies between classes/modules using arrows or lines
Consider using UML diagrams to represent the package dependency
Q41. Balanced Parenthesis No of brackets to make balanced parenthesis Maximum Units on a truck
The question is about balanced parenthesis and finding the maximum units on a truck.
To check if a string of brackets is balanced, we can use a stack data structure.
To find the maximum units on a truck, we need to sort the items by weight and then start adding them to the truck until it reaches its maximum capacity.
Q42. 1. A variation of nodes at a distance of K
A question about finding nodes at a distance of K from a given node in a graph.
Use BFS or DFS to traverse the graph and keep track of the distance from the starting node.
Maintain a visited set to avoid revisiting nodes.
Return all nodes at distance K from the starting node.
Example: Find all nodes at distance 2 from node A in a graph.
Q43. Linked list and operations for array on linked list
Linked list is a data structure where each element points to the next element. Operations like insertion, deletion, traversal can be performed on linked lists.
Linked list is a linear data structure where elements are stored in nodes. Each node contains data and a reference to the next node.
Operations on linked list include insertion, deletion, traversal, and searching.
For example, to insert a new node at the beginning of a linked list, create a new node with the data and poin...read more
Q44. Graph problems with popular algo implementations
Graph problems and popular algo implementations
Shortest Path: Dijkstra's, Bellman-Ford, Floyd-Warshall
Minimum Spanning Tree: Prim's, Kruskal's
Topological Sorting: Kahn's, DFS
Max Flow: Ford-Fulkerson, Edmonds-Karp
Travelling Salesman Problem: Held-Karp, Christofides
Graph Coloring: Greedy, Backtracking
Q45. DSA question. Detect Symmetric Binary tree.
Detect if a binary tree is symmetric.
Check if the left and right subtrees are mirror images of each other.
Use a recursive approach to compare corresponding nodes.
Base case: if both nodes are null, return true.
If one node is null and the other is not, return false.
If the values of the nodes are not equal, return false.
Recursively check if the left subtree of the left node is symmetric to the right subtree of the right node.
Recursively check if the right subtree of the left nod...read more
Q46. DSA only with higher difficulty with SDE3.
The question is about advanced data structures and algorithms for a senior software engineer role.
Focus on advanced data structures like AVL trees, B-trees, and tries
Discuss complex algorithms like Dijkstra's algorithm, A* search algorithm, and dynamic programming
Highlight experience with optimizing time and space complexity
Provide examples of solving challenging coding problems or implementing complex algorithms
Q47. Find the maximum diagonal sum of a binary tree
Find the maximum diagonal sum of a binary tree
Traverse the tree diagonally and keep track of the sum at each diagonal level
Use a hashmap to store the sum at each diagonal level
Return the maximum sum from the hashmap
Q48. Merge point of twi linked list.
Finding the merge point of two linked lists.
Traverse both linked lists to find their lengths.
Move the pointer of the longer list ahead by the difference in lengths.
Iterate both lists simultaneously until the merge point is found.
Q49. How to traverse a linked list
Traversing a linked list involves iterating through each node starting from the head until the end is reached.
Start at the head node
Iterate through each node by following the 'next' pointer until the end is reached
Perform desired operations on each node as needed
Q50. 1. DP + Sliding window problem
DP + Sliding window problem
Dynamic Programming (DP) is a technique to solve optimization problems by breaking them down into smaller subproblems
Sliding window is a technique to solve problems by maintaining a window of elements in an array or string
Combining DP and sliding window can be useful in solving problems that require both techniques
Q51. find treasury island DFS 2D array
Treasury Island can be found using Depth First Search on a 2D array of strings.
Implement a Depth First Search algorithm to traverse the 2D array of strings
Start from a specific point on the island and explore all possible paths
Keep track of visited cells to avoid infinite loops
Return the path that leads to the treasury on the island
Q52. Sum on node in binary tree
Recursively sum the values of nodes in a binary tree
Use a recursive function to traverse the tree and add the values of each node
Base case: if the current node is null, return 0
Recursive step: return the sum of current node value, left subtree sum, and right subtree sum
Q53. How to design amazon
Designing Amazon involves creating a user-friendly e-commerce platform with a vast product selection, efficient search and recommendation algorithms, secure payment processing, and reliable delivery logistics.
Develop a user-friendly interface for easy navigation and product search
Implement recommendation algorithms based on user behavior and preferences
Integrate secure payment processing systems to protect customer information
Establish efficient delivery logistics for timely ...read more
Q54. how to invert 25 bst
To invert a binary search tree (BST), swap the left and right children of each node recursively.
Start from the root node and recursively swap the left and right children of each node.
Repeat this process for all nodes in the BST.
The final result will be the inverted BST.
Q55. create a minesweeper game
Create a classic minesweeper game with a grid of cells to uncover without hitting any mines.
Create a grid of cells with hidden mines randomly placed
Allow the player to uncover cells and reveal numbers indicating nearby mines
Implement logic to end the game if a mine is uncovered or all non-mine cells are revealed
Q56. Reverse a linked list
Reverse a linked list
Iterate through the linked list and change the direction of the pointers
Use three pointers to keep track of current, previous and next nodes
Recursively reverse the linked list
Q57. Number of Islands (on lc)
Count the number of islands in a 2D grid where '1' represents land and '0' represents water.
Iterate through the grid and for each '1' encountered, perform a depth-first search to mark all adjacent '1's as visited.
Increment the island count for each new island found.
Ensure to handle boundary conditions and visited cells properly to avoid infinite loops.
Q58. sort linked lists
Sorting linked lists involves rearranging the nodes in a specific order.
Use a sorting algorithm such as merge sort or quick sort to rearrange the nodes in the linked list.
Iterate through the linked list and compare each node with the next one to determine the correct order.
Consider the time complexity of the sorting algorithm to ensure efficient sorting of the linked list.
Q59. bus transit system design
Designing a bus transit system involves planning routes, schedules, stops, and ticketing systems.
Consider the population density and traffic patterns of the area to determine the number and frequency of bus routes.
Create a network of bus stops strategically located near residential areas, commercial centers, and transportation hubs.
Implement a reliable ticketing system that allows for cashless payments and offers options for daily, weekly, and monthly passes.
Integrate real-ti...read more
Q60. Subsequences of arrays
Subsequences of arrays are all possible combinations of elements in an array.
A subsequence can be of any length, including 0 and the entire array.
The order of elements in a subsequence must be maintained.
The number of possible subsequences of an array of length n is 2^n.
For example, the subsequences of [1, 2, 3] are [], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3].
Q61. Troubleshoot a problem
To troubleshoot a problem, identify the issue, gather information, analyze data, and implement a solution.
Identify the problem by asking questions and gathering information
Analyze data to determine the root cause of the problem
Implement a solution by testing and verifying the fix
Document the problem and solution for future reference
Q62. Merge sort implementation
Merge sort is a divide and conquer algorithm that divides the input array into two halves, sorts them, and then merges them back together.
Divide the array into two halves recursively
Sort each half using merge sort
Merge the sorted halves back together
More about working at Amazon










Top HR Questions asked in Amazon Software Engineer
Interview Process at Amazon Software Engineer

Top Software Engineer Interview Questions from Similar Companies








Reviews
Interviews
Salaries
Users/Month

