
Amazon


30+ Amazon Software Engineer Interview Questions and Answers for Freshers
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. 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
Q8. 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.
Q9. 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
Q10. 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.
Q11. 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
Q12. 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.
Q13. 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.
Q14. 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
Q15. 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
Q16. 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.
Q17. 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.
Q18. 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.
Q19. 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
Q20. 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
Q21. 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
Q22. 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
Q23. 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
Q24. 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
Q25. 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.
Q26. 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
Q27. 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'.
Q28. 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.
Q30. 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
Q31. 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
Q32. 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
Q33. 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
Q34. 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
Q35. 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.
Q36. 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.
Q37. 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
More about working at Amazon










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

Top Software Engineer Interview Questions from Similar Companies








Reviews
Interviews
Salaries
Users/Month

