Top 40 Amazon Coding Interview Questions and Answer
Landing a job at Amazon, one of the world’s leading tech giants is a dream for many aspiring software engineers. However, Amazon’s interview process is known for being rigorous and competitive. To stand out in this challenging environment, candidates must be well-prepared, particularly when it comes to coding interviews. In this blog, we will explore the top Amazon coding interview questions and answers, categorized by experience level to help you prepare. We’ll also share tips on how to effectively prepare for these interviews, to help you approach them with confidence.
Amazon Coding Questions and Answers for Freshers
For freshers, the coding interview at Amazon often focuses on fundamental programming concepts and problem-solving skills. These questions typically assess your understanding of data structures & algorithms and basic coding principles. As a new candidate, you’ll want to demonstrate your technical knowledge and also your ability to think critically and approach problems logically. In this section, we’ll explore common Amazon coding questions with answers that freshers might encounter during their interviews.
Q1. How do you convert a String to a byte array in Java?
Sample Answer: To transform a String into a byte array, use the getBytes() method. Conversely, you can convert a byte array back into a String using the constructor new String(byte[] arr).
Q2. Is it possible to use Strings in switch statements in Java?
Sample Answer: Starting from Java 7, switch statements can accept Strings as cases; earlier versions did not support this feature. For conditional branching involving strings before Java 7, if-else statements are recommended.
Q3. How can you convert a String to uppercase or lowercase in Java?
Sample Answer: In Java, you can convert strings to uppercase or lowercase by using the toUpperCase and toLowerCase methods from the String class. These methods also have variants that accept a Locale argument, allowing for locale-specific conversion rules.
Q4. What does the subSequence method do in the String class?
Sample Answer: Introduced in Java 1.4, the CharSequence interface is implemented by the String class, which includes the subSequence method. This method internally calls the substring method to retrieve a portion of the string.
Q5. What is the purpose of the String class in Java?
Sample Answer: The String class in Java, found in the java.lang package is not a primitive data type like int or long but rather a class that represents sequences of characters. Strings are utilized extensively across Java applications. Notably, strings in Java are immutable and final, meaning their values cannot change after creation. The Java Virtual Machine (JVM) maintains a string pool for storing string objects. You can create a string instance using double quotes and the + operator can be overloaded for concatenation.
Also Read: Amazon SQL Interview Questions
Q6. In what way can you compare two strings within a Java program?
Sample Answer: The String class implements the Comparable interface, providing two versions of the compareTo() method. The compareTo(String anotherString) method compares two strings lexicographically. If the invoking string precedes the argument, it returns a negative integer; if it follows, it returns a positive integer; and if both strings are equal, it returns zero. The equals(String str) method will also return true in this case. Similarly, compareToIgnoreCase(String str) performs a case-insensitive comparison.
Q7. In what way can you convert a String into a character array in Java?
Sample Answer: Since a String is composed of characters, it cannot be converted into a single character directly. You can use the charAt method to access individual characters at specific indices or employ the toCharArray() method to convert an entire string into an array of characters.
Q8. Why is a character array considered a better option than a String for storing passwords in Java?
Sample Answer: A String object in Java is immutable and resides in the string pool. Once created, it remains in memory until garbage collection occurs, which means that even after you finish using the password, it can still be accessed in memory for an extended period. This poses a security risk, as anyone with access to a memory dump can retrieve the password in clear text.
In contrast, using a character array allows you to explicitly set it to blank once you’re finished, giving you control over how long the password remains in memory and mitigating security threats.
Q9. Given an array arr[] of size n, how do you create its prefix sum array prefixSum[]?
Sample Answer: A prefix sum array is constructed such that prefixSum[i] = arr + arr[1] + … + arr[i]. This can be achieved using a loop that iterates through the original array, accumulating the sum.
For example:
def prefix_sum(arr):
prefixSum = [0] * len(arr)
prefixSum[0] = arr[0]
for i in range(1, len(arr)):
prefixSum[i] = prefixSum[i - 1] + arr[i]
return prefixSum
Q10. Given an array of distinct integers, how can you find all pairs with the minimum absolute difference?
Sample Answer: First, sort the array, then iterate through it to find pairs with the smallest difference. Here’s the code for finding all pairs with the minimum absolute difference:
def min_abs_diff_pairs(arr):
arr.sort()
min_diff = float('inf')
pairs = []
for i in range(len(arr) - 1):
diff = abs(arr[i] - arr[i + 1])
if diff < min_diff:
min_diff = diff
pairs = [(arr[i], arr[i + 1])]
elif diff == min_diff:
pairs.append((arr[i], arr[i + 1]))
return pairs
Q11. Design a function to return the optimal locker for an incoming package.
Sample Answer: The optimal locker can be determined based on availability or proximity to the delivery point. A simple approach could be to find the first available locker as follows:
def optimal_locker(lockers):
for i, locker in enumerate(lockers):
if locker.is_available():
return i
return None
Q12. Given an integer array nums, how do you calculate the sum of all subarray ranges?
Sample Answer: The range of a subarray is defined as the difference between its maximum and minimum elements. We can use nested loops to compute this in the following way:
def subarray_ranges(nums):
total_sum = 0
n = len(nums)
for i in range(n):
for j in range(i, n):
subarray = nums[i:j+1]
total_sum += max(subarray) - min(subarray)
return total_sum
Q13. Given an array of entities and an integer N, how do you remove every Nth entity until one remains?
Sample Answer: This can be done using a circular approach. Here is the code for implementing this:
def last_remaining_entity(entities, N):
index = 0
while len(entities) > 1:
index = (index + N - 1) % len(entities)
entities.pop(index)
return entities
Amazon Coding Interview Questions and Answers for Mid-level Professionals
Mid-level professionals face a different set of expectations during their coding interviews at Amazon. For this experience level, the focus shifts towards more complex problem-solving scenarios. Candidates are expected to demonstrate their experience and how they can apply their skills to solve problems. This section will cover typical Amazon coding interview questions and answers for mid-level candidates, to help you prepare effectively for your interview.
Q14. How would you search for an element in a sorted array that has infinite length?
Sample Answer: We can use exponential search to find bounds and then perform binary search within those bounds. Here is the code for implementing this:
def search_in_infinite_array(arr, target):
low, high = 0, 1
while arr[high] < target:
low = high
high *= 2
while low <= high:
mid = low + (high - low) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
Q15. Given an integer array nums and a target integer, how do you find indices of two numbers that add up to that target?
Sample Answer: A hash map can be used to store indices while iterating through the array. Here is the code for implementing this:
def two_sum(nums, target):
num_map = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_map:
return [num_map[complement], i]
num_map[num] = i
return []
Q16. Given a sorted dictionary of words from an alien language, how can you find the order of characters?
Sample Answer: This can be solved using topological sorting based on character dependencies derived from adjacent words. Here is the code for implementing this:
from collections import defaultdict
def alien_order(words):
graph = defaultdict(set)
indegree = {char: 0 for word in words for char in word}
for i in range(len(words) - 1):
w1, w2 = words[i], words[i + 1]
for c1, c2 in zip(w1, w2):
if c1 != c2:
if c2 not in graph[c1]:
graph[c1].add(c2)
indegree[c2] += 1
break
queue = [char for char in indegree if indegree[char] == 0]
order = []
while queue:
char = queue.pop(0)
order.append(char)
for neighbor in graph[char]:
indegree[neighbor] -= 1
if indegree[neighbor] == 0:
queue.append(neighbor)
return ''.join(order) if len(order) == len(indegree) else ""
Q17. Given bus capacity and passenger details including pickup and drop locations, how do you check if all passengers can reach their destinations?
Sample Answer: We can simulate bus operations by tracking current passengers at each pickup/drop point by using the code, as follows:
def can_all_passengers_reach(passenger_data, capacity):
current_passengers = 0
for passengers, pickup, drop in passenger_data:
current_passengers += passengers
if current_passengers > capacity:
return False
current_passengers -= passengers
return True
Q18. Find the sum of all numbers stored in a linked list.
Sample Answer: Go through each node and accumulate the values. Here is the code for implementing this:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def sum_linked_list(head):
total_sum = 0
current_node = head
while current_node is not None:
total_sum += current_node.val
current_node = current_node.next
return total_sum
Q19. Given two non-empty linked lists representing non-negative integers stored in reverse order, how would you add them?
Sample Answer: Here’s a Python function to add two linked lists representing non-negative integers stored in reverse order. It uses a carry to handle sums greater than 10 during the traversal of both lists.
def add_two_numbers(l1, l2):
dummy_head = ListNode(0)
current_node = dummy_head
carry = 0
while l1 or l2 or carry:
val1 = (l1.val if l1 else 0)
val2 = (l2.val if l2 else 0)
total_sum = val1 + val2 + carry
carry, digit_value = divmod(total_sum, 10)
current_node.next = ListNode(digit_value)
current_node = current_node.next
l1 = (l1.next if l1 else None)
l2 = (l2.next if l2 else None)
return dummy_head.next
Q20. In a linked list representing chapter page counts, where pages are read from both the start and end each day, which day had the highest number of total pages read?
Sample Answer: Here’s a Python function that finds the day with the maximum pages read when chapters (as a linked list) are read from both ends daily, using two pointers to track the reading process.
def max_pages_read(head):
fast_pointer, slow_pointer = head, head
day_count=0
max_pages=0
while fast_pointer and fast_pointer.next:
day_count+=1
max_pages=max(max_pages,(slow_pointer.val+fast_pointer.val))
slow_pointer=slow_pointer.next
fast_pointer=fast_pointer.next.next
return day_count,max_pages
Also Read: Amazon Interview Questions for SDE
Q21. Write a program to find all concatenated words formed by at least two shorter words.
Sample Answer: Here’s a Python program to find all concatenated words that are formed by at least two shorter words, using dynamic programming to check for valid combinations.
def find_concatenated_words(words):
word_set=set(words)
result=[]
def can_form(word):
dp=[False]*(len(word)+1)
dp=True
for end in range(1,len(word)+1):
for start in range(end):
if dp[start] and word[start:end] in word_set:
dp[end]=True
return dp[len(word)]
for word in words:
word_set.remove(word)
if can_form(word):
result.append(word)
return result
Q22. Given a string ‘s’, how would you identify its longest palindromic substring?
Sample Answer: To find the longest palindromic substring in a given string using dynamic programming or the expand-around-center technique, I would apply the following logic.
def longest_palindrome(s):
start, end=0,0
for i in range(len(s)):
len_odd=expand_around_center(s,i,i)
len_even=expand_around_center(s,i,i+1)
max_len=max(len_odd,len_even)
if max_len>(end-start):
start=i-(max_len-1)//2
end=i+max_len//2
return s[start:end+1]
def expand_around_center(s,left,right):
while left>=0 and right<len(s) and s[left]==s[right]:
left-=1
right+=1
return right-left-1
Q23. Write code to reverse a string and stack it.
Sample Answer: To reverse a string using a stack, you can follow this approach:
def reverse_string(s):
stack=[]
for char in s:
stack.append(char)
reversed_str=''.join(stack[::-1])
return reversed_str
This code pushes each character of the string onto a stack and then constructs the reversed string by joining the characters in the stack in reverse order.
Q24. Given two strings with backspace characters (#), determine if they are equal after processing.
Sample Answer: To check if two strings are equal after processing backspace characters (#), you can implement the following solution:
def backspace_compare(s: str,t: str)-> bool:
def process_string(string):
result=[]
for char in string:
if char!='#':
result.append(char)
elif result:
result.pop()
return ''.join(result)
return process_string(s)==process_string(t)
This function processes each string by building a list of characters, ignoring characters that are removed by backspaces, and then compares the final results.
Q25. How would you calculate this length given string s?
Sample Answer: To determine the length of the longest substring without repeating characters, consider the following implementation:
def length_of_longest_substring(s):
char_index={}
left,max_length=0,0
for right,char in enumerate(s):
if char in char_index:
left=max(left,char_index[char]+1)
char_index[char]=right
max_length=max(max_length,right-left+1)
return max_length
Amazon Coding Interview Questions with Answers for Experienced Professionals
Advanced professionals entering the interview process at Amazon will encounter highly technical and challenging programming questions designed to test their depth of knowledge in software engineering. In this section, we’ll explore Amazon coding test questions you might face as an advanced candidate.
Q26. Find the number of unique letters present across all substrings of string s.
Sample Answer: To count the number of unique letters present across all substrings of a given string, you can use the following approach:
def unique_letter_count(s):
unique_letters=set()
for start in range(len(s)):
seen=set()
for end in range(start,len(s)):
seen.add(s[end])
unique_letters.update(seen)
return len(unique_letters)
This function iterates through each substring and accumulates unique characters in a set, which ensures that duplicates are not counted.
Q27. Given string s which represents an expression with constraints on substring size and unique characters count under certain limits. How would one evaluate this expression?
Sample Answer: To evaluate an expression represented by a string with constraints on substring size and unique character counts, you can implement the following function:
def max_occurrences(s,maxLetters,minSize,maxSize):
count={}
n=len(s)
# Count occurrences of valid substrings
for size in range(minSize,maxSize+1):
for i in range(n-size+1):
substring=s[i:i+size]
unique_chars=len(set(substring))
# Check constraints
if unique_chars<=maxLetters:
count[substring]=count.get(substring,0)+1
# Return maximum occurrences
return max(count.values(),default=0)
Q28. Given string s which represents an expression, how would one evaluate this expression and obtain its value?
Sample Answer: The eval function could be used directly. However, implementing it manually ensures an understanding of operator precedence. To evaluate an expression represented as a string, you can use the following approach:
def evaluate_expression(expression):
# Implementing basic evaluation logic
tokens=expression.split()
stack=[]
operators={'+':lambda x,y:x+y,'-':lambda x,y:x-y}
# Evaluate based on operator precedence
for token in tokens:
if token.isdigit():
stack.append(int(token))
elif token in operators:
b,a=stack.pop(),stack.pop()
stack.append(operators[token](a,b))
# Final result
return stack[-1]
Q29. Given the string representation of heads/tails, how many flips are needed so that all heads precede tails?
Sample Answer: To determine the minimum number of flips needed so that all heads precede tails in a given string representation, you can use the following method:
def min_flips_to_heads_first(s):
flips=0
# Count transitions
prev='H'
for char in s:
if char=='T' and prev=='H':
flips+=1
prev=char
# Return total flips needed
return flips
This function iterates through the string, counting transitions from heads to tails, which indicates where flips would be necessary to achieve the desired order.
Q30. Given a dictionary with words, how would one find the shortest chain between start and target words using the BFS/DFS approach?
Sample Answer: To find the shortest chain between a start and target word using a breadth-first search (BFS) approach, here’s a Python implementation:
from collections import deque
def shortest_chain(start, target, dictionary):
if start == target:
return [start] # Early exit if start equals target
queue = deque([(start, [start])]) # (current word, path)
visited = set([start])
while queue:
word, path = queue.popleft()
# Check each transformation (letter by letter)
for i in range(len(word)):
# Iterate through alphabet
for c in 'abcdefghijklmnopqrstuvwxyz':
new_word = word[:i] + c + word[i+1:]
# Check if we've reached the target word
if new_word == target:
return path + [new_word]
# If the new word is valid and not visited
if new_word not in visited and new_word in dictionary:
visited.add(new_word)
queue.append((new_word, path + [new_word]))
# No valid transformation chain found
return []
Q31. In matrix grid representation with entrance points, how does one determine the shortest path to avoiding obstacles using the BFS/DFS approach?
Sample Answer: BFS will be effective here due to level-wise exploration ensuring the shortest path discovery. Here is the code for implementing this:
from collections import deque
def shortest_path(matrix, start, end):
rows, cols = len(matrix), len(matrix[0])
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] # Right, Down, Left, Up
queue = deque([(start[0], start[1], 0)]) # (row, col, distance)
visited = set()
visited.add(start)
while queue:
x, y, distance = queue.popleft()
# Check if we've reached the end point
if (x, y) == end:
return distance
# Explore all four possible directions
for dx, dy in directions:
nx, ny = x + dx, y + dy
# Check if within bounds, path is open, and the cell is not visited
if 0 <= nx < rows and 0 <= ny < cols and matrix[nx][ny] == '_' and (nx, ny) not in visited:
visited.add((nx, ny))
queue.append((nx, ny, distance + 1))
return -1 # Return -1 if no path exists
Q32. Given the root of a binary tree, how would you reverse it?
Sample Answer: This can be achieved using a recursive approach to swap left and right children. Here is the code for implementing this:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def reverse_binary_tree(root):
if not root:
return None
root.left, root.right = root.right, root.left
reverse_binary_tree(root.left)
reverse_binary_tree(root.right)
return root
Q33. Given a binary tree where each node has coins, how can you determine the minimum number of moves to ensure each node has exactly one coin?
Sample Answer: To determine the minimum number of moves needed to distribute coins in a binary tree so that each node has exactly one coin, you can approach it using a depth-first search (DFS) method:
def min_moves_to_distribute_coins(root):
def dfs(node):
if not node:
return 0
left_moves = dfs(node.left)
right_moves = dfs(node.right)
# Calculate moves needed for this node
total_moves = left_moves + right_moves + (node.val - 1)
return total_moves
return dfs(root)
Q34. Given the root of a binary tree, how would you print its nodes in zig-zag order?
Sample Answer: To print the nodes of a binary tree in a zig-zag (or spiral) order, you can alternate the traversal direction at each level:
from collections import deque
def zigzag_level_order(root):
if not root:
return []
result = []
current_level = deque([root])
left_to_right = True
while current_level:
level_values = []
for _ in range(len(current_level)):
node = current_level.popleft()
level_values.append(node.val)
if left_to_right:
if node.left: current_level.append(node.left)
if node.right: current_level.append(node.right)
else:
if node.right: current_level.append(node.right)
if node.left: current_level.append(node.left)
result.append(level_values)
left_to_right = not left_to_right
return result
Q35. Given the root of a binary tree, how would you find the maximum path sum of any non-empty path?
Sample Answer: To find the maximum path sum of any non-empty path in a binary tree, you can use this approach:
def max_path_sum(root):
max_sum = float('-inf')
def helper(node):
nonlocal max_sum
if not node:
return 0
left_gain = max(helper(node.left), 0)
right_gain = max(helper(node.right), 0)
price_new_path = node.val + left_gain + right_gain
max_sum = max(max_sum, price_new_path)
return node.val + max(left_gain, right_gain)
helper(root)
return max_sum
This function works by recursively finding the maximum gain from each node in the tree while keeping track of the highest path sum found so far. The helper function ignores negative gains (since they would reduce the sum) and ensures that the sum of the path is as large as possible.
Also Read: Amazon Software Developer Interview Questions
Q36. Given two trees, how can you check if they are mirrors of one another?
Sample Answer: You can check if two trees are mirrors by comparing their nodes recursively. The function ensures that the root values match and that the left subtree of one tree is a mirror of the right subtree of the other. Here is the code for implementing this:
def are_mirrors(tree1, tree2):
if not tree1 and not tree2:
return True
if not tree1 or not tree2:
return False
return (tree1.val == tree2.val) and \
are_mirrors(tree1.left, tree2.right) and \
are_mirrors(tree1.right, tree2.left)
Q37. Write code to merge two sorted integer streams into one sorted stream.
Sample Answer: To merge two sorted integer streams into a single sorted stream, you can use a min-heap. This allows you to efficiently combine the two streams while maintaining the sorted order. Here is the code for implementing this:
import heapq
def merge_sorted_streams(stream1, stream2):
merged_stream = []
heapq.heapify(stream1)
heapq.heapify(stream2)
while stream1 or stream2:
if stream1 and (not stream2 or stream1[0] <= stream2[0]):
merged_stream.append(heapq.heappop(stream1))
else:
merged_stream.append(heapq.heappop(stream2))
return merged_stream
Q38. How do you print a sequence starting with N without using loops?
Sample Answer: You can print a sequence starting from N without using loops by using recursion. The function prints the current number and then calls itself with the next lower number until it reaches zero.
Here is the code for implementing this:
def print_sequence(n):
print(n)
if n > 0:
print_sequence(n-1)
print_sequence(5) # Example usage starting from 5
Q39. Given cities and the distances between them, how would you find the shortest route that visits every city exactly once and returns to the start?
Sample Answer: This problem can be approached using dynamic programming with bit masking or by applying heuristics like genetic algorithms for larger datasets. Here is the code for implementing this:
from itertools import permutations
def shortest_route(cities):
min_distance = float('inf')
best_route = []
for perm in permutations(cities):
distance = calculate_distance(perm) # Assume this function calculates total distance for given route.
if distance < min_distance:
min_distance = distance
best_route = perm
return best_route
def calculate_distance(route):
# Implement logic to calculate total distance based on route order.
pass
Q40. Can you explain the time and space complexities of the algorithm you developed to solve the problem of sorting a list of integers? Please provide details on how these complexities impact the performance and scalability of your solution.
Sample Answer: The time complexity of my sorting algorithm depends on the specific algorithm used. For instance, if I implemented a general sorting algorithm like QuickSort or MergeSort, the time complexity would be O(n log n) on average. However, if I used a specialized algorithm such as Counting Sort, the time complexity could be O(n) under certain conditions (e.g. when the range of input values is limited). Regarding space complexity, it can be O(1) for in-place algorithms like QuickSort, or O(n) for algorithms that require additional space, such as MergeSort.
I believe understanding these complexities is essential because they help me assess how well the solution will perform with larger datasets and ensure that it can scale effectively in real-world applications. This awareness allows me to make informed decisions about algorithm selection based on the specific requirements and constraints of the problem I am addressing.
Amazon Coding Interview Interview Preparation Tips
Preparation is key when it comes to succeeding in coding interviews at Amazon. In this section, we will provide you with tips and strategies to enhance your interview readiness. We’ll cover essential areas that will equip you to navigate the interview process confidently. Here are the key areas to focus on for Amazon coding interview preparation:
- Focus on Data Structures and Algorithms: Spend dedicated time practicing problems on DSA involving hash tables, trees, graphs, and dynamic programming. Amazon frequently asks questions that have multiple valid solutions, expecting you to discuss the pros and cons of each.
- Develop Strong Code Organization Skills: Amazon values clean, maintainable code. Practice writing code that’s functional, well-organized, and easy to understand. Implement proper error handling, write clear variable names, and structure your code in a way that makes it easy to modify or extend.
- Master the STAR Method: When discussing your experiences, use the Situation, Task, Action, Result (STAR) method. This structured approach helps you concisely communicate your past experiences and achievements. Prepare several STAR stories that demonstrate your technical skills, leadership abilities, and problem-solving capabilities.
- Time Management Practice: Amazon interviews typically last 45-60 minutes. Practice solving problems within this timeframe, including explanation time. Break it down into 5 minutes for problem understanding, 5 minutes for discussing approach, 25-30 minutes for coding, and 5-10 minutes for testing.
- Mock Interview Practice: Conduct mock interviews with peers or through online platforms. Focus on explaining your thought process clearly while coding, handling hints, and maintaining professional composure under pressure. Record your mock interviews if possible to identify areas for improvement.
- Code Review Preparation: Amazon values developers who can both write and review code effectively. Practice reviewing others’ code and providing constructive feedback. Focus on identifying potential bugs, performance issues, and maintainability concerns. This skill demonstrates your ability to contribute to team code quality and mentor others.
Conclusion
As you try to secure a coding position at Amazon, remember that thorough preparation is essential. In this guide, we’ve compiled a list of the top 40 Amazon coding interview questions and answers to help with your preparations. By understanding the types of questions asked at different levels and following our preparation tips, you’ll be able to ace the interview process. Want to understand the different types of questions asked at Amazon? Check out our guide on Amazon interview questions and Answers.
FAQs
Answer: Common languages include Java, Python, C++, and JavaScript. It’s essential to choose a language you are comfortable with, as fluency in syntax and libraries can save you valuable time during the interview.
Answer: Books and online courses focused on algorithms and data structures can deepen your understanding of key concepts that are frequently asked in interviews. Engaging in mock interviews with peers can also enhance your readiness.
Answer: Yes. Asking clarifying questions shows engagement and helps ensure you understand the problem correctly before diving into a solution.