Add office photos
Amazon logo
Engaged Employer

Amazon

Verified
4.1
based on 25.2k Reviews
Video summary
Proud winner of ABECA 2024 - AmbitionBox Employee Choice Awards
Filter interviews by

2000+ Amazon Interview Questions and Answers

Updated 28 Feb 2025
Popular Designations

Q1. Maximum Subarray Sum Problem Statement

Given an array of integers, determine the maximum possible sum of any contiguous subarray within the array.

Example:

Input:
array = [34, -50, 42, 14, -5, 86]
Output:
137
E...read more
Ans.

Find the maximum sum of any contiguous subarray within an array of integers.

  • Iterate through the array and keep track of the maximum sum of subarrays encountered so far.

  • At each index, decide whether to include the current element in the subarray or start a new subarray.

  • Use Kadane's algorithm to efficiently find the maximum subarray sum in O(N) time complexity.

View 41 more answers
right arrow

Q2. Minimum Number of Platforms Needed Problem Statement

You are given the arrival and departure times of N trains at a railway station for a particular day. Your task is to determine the minimum number of platform...read more

Ans.

Determine the minimum number of platforms needed at a railway station based on arrival and departure times of trains.

  • Sort the arrival and departure times in ascending order.

  • Use two pointers to keep track of overlapping schedules.

  • Increment the platform count when a new train arrives before the previous one departs.

  • Return the maximum platform count needed.

View 6 more answers
right arrow
Amazon Interview Questions and Answers for Freshers
illustration image

Q3. Every time I enter a temple my money gets doubled and while leaving u have to donate 100 like this I go to 4 temple and when I leave the 4th temple I will have no money left so what was the money I had when I e...

read more
Ans.

The person had no money when they entered the first temple.

  • The person's money gets doubled every time they enter a temple.

  • They have to donate 100 when leaving each temple.

  • After visiting 4 temples, they have no money left.

  • Therefore, they must have had no money when they entered the first temple.

View 49 more answers
right arrow

Q4. If a seller wants to sell a phone worth 60k at 7k on amazon then would you allow him? If not then why? And what are the things you wanna confirm before allowing him to sell his product in your website?

Ans.

No, I would not allow the seller to sell the phone at such a low price. I would confirm the authenticity of the product and the seller's credentials.

  • Confirm authenticity of the product

  • Verify seller's credentials

  • Check for any suspicious activity or fraud

  • Ensure compliance with Amazon's policies and guidelines

View 16 more answers
right arrow
Discover Amazon interview dos and don'ts from real experiences

Q5. What is the difference between a good customer service and bad customer service?

Ans.

Good customer service is helpful, efficient, and personalized, while bad customer service is unresponsive, rude, and impersonal.

  • Good customer service is helpful and goes above and beyond to assist customers.

  • Good customer service is efficient and resolves issues promptly.

  • Good customer service is personalized and treats each customer as an individual.

  • Bad customer service is unresponsive and fails to address customer concerns.

  • Bad customer service is rude and lacks empathy toward...read more

View 142 more answers
right arrow

Q6. Fenwick Tree Problem Statement

You are provided with an array/list ARR consisting of 'N' integers, along with 'Q' queries. Each query can be of one of the following two types:

  • Type 1 (Range Sum): Given two int...read more
Ans.

Implement Fenwick Tree to handle range sum and point update queries on an array.

  • Implement Fenwick Tree data structure to efficiently handle range sum and point update queries.

  • For range sum queries, use prefix sum technique to calculate the sum of elements in the given range.

  • For point update queries, update the Fenwick Tree structure accordingly.

  • Handle each query type separately and output the required results.

  • Ensure to follow the constraints provided in the problem statement.

View 2 more answers
right arrow
Are these interview questions helpful?

Q7. A man walks into his office and every time if there are people in the lift he takes it till 10th floor till his cabin if he is alone he only takes it till 7 and returning back he takes the lift till ground floo...

read more
Ans.

The man takes the lift till 7th floor when alone because he is too short to reach the button for the 10th floor.

  • The man takes the lift till 10th floor when there are people because they can press the button for him.

  • He takes the lift till ground floor when returning because he doesn't need to go to his cabin anymore.

  • This is a riddle question.

View 27 more answers
right arrow

Q8. Fish Eater Problem Statement

In a river where water flows from left to right, there is a sequence of 'N' fishes each having different sizes and speeds. The sizes of these fishes are provided in an array called ...read more

Ans.

Given a river with fishes of different sizes and speeds, determine how many fishes survive after encounters.

  • Iterate through the array of fishes and simulate encounters between fishes to determine survivors

  • Use a stack to keep track of surviving fishes

  • Compare sizes of fishes to determine which fish eats the other

View 1 answer
right arrow
Share interview questions and help millions of jobseekers 🌟
man with laptop

Q9. 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 more
Ans.

The longest continuous patch of a road repaired by a contractor is determined.

  • Iterate through the updates and keep track of the start and end points of each patch

  • Calculate the length of each patch and update the longest patch if necessary

  • Return the start and end points of the longest patch

View 1 answer
right arrow

Q10. Longest Common Subsequence Problem Statement

Given two strings STR1 and STR2, determine the length of their longest common subsequence.

A subsequence is a sequence that can be derived from another sequence by d...read more

Ans.

The task is to find the length of the longest common subsequence between two given strings.

  • Implement a function to find the longest common subsequence between two strings

  • Use dynamic programming to solve the problem efficiently

  • Iterate through the strings to find the common subsequence

  • Handle edge cases like empty strings or strings with no common subsequence

View 4 more answers
right arrow

Q11. Permutation in String Problem Statement

Determine if the string str2 contains a permutation of the string str1 as one of its substrings.

Input:

The first line contains an integer 'T', representing the number of...read more
Ans.

Check if a permutation of one string is a substring of another string.

  • Create a frequency map of characters in str1.

  • Iterate through str2 with a window of size N and check if the frequency map matches.

  • Return 'Yes' if a permutation is found, 'No' otherwise.

Add your answer
right arrow

Q12. Fire in the Cells Problem Statement

Given a matrix MAT of size N * M, where each cell is either on fire or safe, determine if a person can reach an escape cell without being burnt. The person starts from a give...read more

Ans.

Determine if a person can reach an escape cell without encountering fire in a matrix.

  • Check if the person can reach an escape cell without encountering fire by simulating the movement of the person and fire spread.

  • If the person can reach an escape cell, return the time taken; otherwise, return -1.

  • Consider the constraints and edge cases while implementing the solution.

Add your answer
right arrow

Q13. Find All Pairs Adding Up to Target

Given an array of integers ARR of length N and an integer Target, your task is to return all pairs of elements such that they add up to the Target.

Input:

The first line conta...read more
Ans.

Given an array of integers and a target, find all pairs of elements that add up to the target.

  • Iterate through the array and for each element, check if the target minus the element exists in a hash set.

  • If it exists, add the pair to the result. If not, add the element to the hash set.

  • Handle cases where the same element is used twice to form a pair.

  • Return (-1, -1) if no pair is found.

Add your answer
right arrow

Q14. Maximum Path Sum Between Two Leaves

Given a non-empty binary tree where each node has a non-negative integer value, determine the maximum possible sum of the path between any two leaves of the given tree.

Expla...read more

Ans.

Find the maximum path sum between two leaf nodes in a binary tree.

  • Traverse the tree to find the maximum path sum between two leaf nodes

  • Consider both cases where the path passes through the root and where it doesn't

  • Use recursion to calculate the sum of paths from each leaf node to the root

View 1 answer
right arrow

Q15. If a customer placed an order for DSLR camera worth 50k and chose COD as payment option, how will you investigate this situation?

Ans.

I would verify the authenticity of the order and the customer before proceeding with the delivery.

  • Check the customer's order history and account details

  • Verify the customer's contact information

  • Confirm the delivery address

  • Check for any suspicious activity or signs of fraud

  • Contact the customer to confirm the order and payment method

  • If necessary, involve law enforcement or security personnel

View 9 more answers
right arrow

Q16. Delete Alternate Nodes from a Singly Linked List

Given a Singly Linked List of integers, remove all the alternate nodes from the list.

Input:

The first and the only line of input will contain the elements of th...read more
Ans.

Remove alternate nodes from a singly linked list of integers.

  • Traverse the linked list and skip every alternate node while updating the next pointers.

  • Make sure to handle cases where there are less than 3 nodes in the list.

  • Update the next pointers accordingly to remove alternate nodes.

  • Example: Input: 10 20 30 40 50 60 -1, Output: 10 30 50

Add your answer
right arrow

Q17. Find Pair With Smallest Difference Problem Statement

Given two unsorted arrays of non-negative integers, arr1 and arr2 with sizes N and M, determine the pair of elements (one from each array) which have the sma...read more

Ans.

Find the pair of elements with the smallest absolute difference from two unsorted arrays.

  • Sort both arrays to simplify finding the pair with the smallest difference.

  • Use two pointers approach to iterate through both arrays and find the pair with the smallest difference.

  • Keep track of the minimum absolute difference and update it as you find smaller differences.

  • Return the minimum absolute difference once all pairs have been checked.

View 1 answer
right arrow

Q18. Car Pooling Problem Statement

You are tasked with driving a cab that moves in a straight line, only forward, and initially has 'C' empty seats available for passengers.

Given 'N' trips, each defined by three in...read more

Ans.

The problem involves determining if a cab with a certain capacity can successfully pick up and drop off passengers at specified points for multiple trips.

  • Create a function that takes in the car's capacity, number of trips, and trip details as input

  • Iterate through each trip and check if the total number of passengers picked up and dropped off is within the car's capacity

  • Return 'True' if all trips can be successfully completed, 'False' otherwise

Add your answer
right arrow

Q19. Maximum Sum of Non-Adjacent Elements

Given an array/list of ‘N’ integers, your task is to return the maximum sum of the subsequence where no two elements are adjacent in the given array/list.

Example:

Input:
T ...read more
Ans.

Find the maximum sum of non-adjacent elements in an array.

  • Use dynamic programming to keep track of the maximum sum at each index, considering whether to include the current element or skip it.

  • At each index, the maximum sum is either the sum of the current element and the element two positions back, or the sum at the previous index.

  • Iterate through the array and update the maximum sum at each index accordingly.

  • Return the maximum sum obtained at the last index as the final resul...read more

Add your answer
right arrow

Q20. Search for Indices with Given Difference and Distance

You are provided with an array containing 'N' non-negative integers, along with two other non-negative integers 'K' and 'M'. Your task is to identify and re...read more

Ans.

Find a pair of indices in an array with given difference and distance constraints.

  • Iterate through the array and check all possible pairs of indices to satisfy the conditions

  • Use nested loops to compare each pair of indices and their corresponding elements

  • Return 'valid' if a pair of indices is found that meets the conditions, otherwise return 'invalid'

Add your answer
right arrow

Q21. First Missing Positive Problem Statement

You are provided with an integer array ARR of length 'N'. Your objective is to determine the first missing positive integer using linear time and constant space. This me...read more

Ans.

The task is to find the lowest positive integer that does not exist in the given array of integers.

  • Iterate through the array and mark the positive integers as visited using the array indices.

  • Iterate through the marked array and return the index of the first unmarked element.

  • If all positive integers are marked, return the length of the array + 1 as the missing positive integer.

Add your answer
right arrow

Q22. Sum of Minimum and Maximum Elements of All Subarrays of Size K

You are provided with an array containing N integers along with an integer K. Your task is to compute the total sum of the minimum and maximum elem...read more

Ans.

Calculate the sum of minimum and maximum elements of all subarrays of size K in an array.

  • Iterate through the array and maintain a deque to store the indices of elements in the current window of size K.

  • Keep track of the minimum and maximum elements in the current window using the deque.

  • Calculate the sum of minimum and maximum elements for each subarray of size K and return the total sum.

Add your answer
right arrow

Q23. Spiral Matrix Problem Statement

You are provided with a 2-D array called MATRIX with dimensions N x M containing integers. Your task is to return the matrix's elements in a spiral order.

Example:

Spiral path of a matrix

Input:

The fi...read more
Ans.

The task is to return the elements of a 2-D array in a spiral order.

  • Traverse the matrix in a spiral order by moving right, down, left, and up.

  • Keep track of the boundaries of the matrix as you move along.

  • Handle cases where the matrix is not a square (N != M).

Add your answer
right arrow

Q24. Best Time To Buy and Sell Stock Problem Statement

You are given an array 'PRICES' of 'N' integers, where 'PRICES[i]' represents the price of a certain stock on the i-th day. An integer 'K' is also provided, ind...read more

Ans.

Find the maximum profit achievable with at most K transactions by buying and selling stocks.

  • Iterate through the array and keep track of the minimum price to buy and maximum profit for each transaction.

  • Use dynamic programming to store the maximum profit at each day with each possible number of transactions.

  • Consider edge cases like when K is 0 or when the array is empty.

  • Example: For input N = 6, PRICES = [3, 2, 6, 5, 0, 3], K = 2, the output should be 7.

Add your answer
right arrow

Q25. String Transformation Problem Statement

Given a string str of length N, perform a series of operations to create a new string:

  1. Select the smallest character from the first 'K' characters of the string, remove ...read more
Ans.

The problem involves selecting the smallest character from the first 'K' characters of a string and appending it to a new string until the original string is empty.

  • Iterate through the string, selecting the smallest character from the first 'K' characters each time.

  • Remove the selected character from the original string and append it to the new string.

  • If fewer than 'K' characters remain, sort and append them in order.

  • Repeat the process until the original string is empty.

Add your answer
right arrow

Q26. Stock Trading Maximum Profit Problem

Given the stock prices for 'N' days, your goal is to determine the maximum profit that can be achieved. You can buy and sell the stocks any number of times but can only hold...read more

Ans.

The goal is to determine the maximum profit that can be achieved by buying and selling stocks on different days.

  • Iterate through the stock prices and buy on days when the price is lower than the next day, and sell on days when the price is higher than the next day.

  • Calculate the profit by summing up the differences between buying and selling prices.

  • Repeat the process for each test case and output the maximum profit achieved.

  • Example: For prices [7, 1, 5, 3, 6, 4], buy on day 2 a...read more

Add your answer
right arrow

Q27. Container with Most Water Problem Statement

Given a sequence of 'N' space-separated non-negative integers A[1], A[2], ..., A[i], ..., A[n], where each number in the sequence represents the height of a line draw...read more

Ans.

Given a sequence of non-negative integers representing the height of lines on a cartesian plane, find two lines that form a container with the maximum area of water.

  • Use two pointers approach to find the maximum area

  • Start with the widest container and gradually move the pointers towards each other

  • Calculate the area at each step and update the maximum area

  • The area is calculated as the minimum height of the two lines multiplied by the distance between them

Add your answer
right arrow

Q28. What happens if a seller is adamant on not understanding a policy and you can't do anything plus you cannot say No to the seller too?

Ans.

If a seller is adamant on not understanding a policy, try to explain it in a different way and provide examples. If they still refuse, escalate to a higher authority.

  • Try to understand the seller's perspective and address their concerns

  • Provide clear and concise explanations of the policy

  • Use examples to illustrate the policy

  • If the seller still refuses to comply, escalate the issue to a higher authority

View 10 more answers
right arrow

Q29. Detect Cycle in a Directed Graph

You are provided with a directed graph composed of 'N' nodes. You have a matrix called 'EDGES' with dimensions M x 2, which specifies the 'M' edges in the graph. Each edge is di...read more

Ans.

Detect cycle in a directed graph using depth-first search (DFS) algorithm.

  • Use DFS to traverse the graph and detect back edges indicating a cycle.

  • Maintain a visited array to keep track of visited nodes during traversal.

  • If a node is visited again during traversal and it is not the parent node, then a cycle exists.

  • Return true if a cycle is detected, false otherwise.

Add your answer
right arrow

Q30. Rotting Oranges Problem Statement

You are given a grid containing oranges where each cell of the grid can contain one of the three integer values:

  • 0 - representing an empty cell
  • 1 - representing a fresh orange...read more
Ans.

Find the minimum time required to rot all fresh oranges in a grid.

  • Use Breadth First Search (BFS) to simulate the rotting process.

  • Track the time taken to rot all fresh oranges.

  • Return -1 if not all fresh oranges can be rotten.

  • Handle edge cases like empty grid or no fresh oranges.

  • Example: For the given grid, it takes 4 seconds to rot all fresh oranges.

Add your answer
right arrow

Q31. Find Pair Sum Equal to K

Given an integer array arr and an integer 'Sum', find and return the total number of pairs in the array which, when added together, result in the 'Sum'.

Note:
The array can contain dupl...read more
Ans.

Find total number of pairs in array that sum to given value.

  • Use a hashmap to store frequency of each element in the array.

  • Iterate through the array and check if (Sum - current element) exists in the hashmap.

  • Increment count of pairs if found and update hashmap accordingly.

Add your answer
right arrow

Q32. Rotten Oranges Problem Statement

Given a grid containing oranges in three possible states:

  • Value 0 - Empty cell
  • Value 1 - Fresh orange
  • Value 2 - Rotten orange

Every second, any fresh orange adjacent (4-direct...read more

Ans.

Given a grid with fresh and rotten oranges, determine the minimum time for all oranges to become rotten.

  • Create a queue to store the coordinates of rotten oranges and perform BFS to rot adjacent fresh oranges

  • Track the time taken to rot all oranges and return -1 if some fresh oranges remain

  • Handle edge cases like empty grid or no fresh oranges present

  • Example: For input grid = [[2,1,1],[1,1,0],[0,1,1]], the minimum time to rot all oranges is 4

Add your answer
right arrow

Q33. Counting Derangements Problem

A derangement is a permutation of 'N' elements, where no element appears in its original position. For instance, a derangement of {0, 1, 2, 3} is {2, 3, 1, 0} because each element ...read more

Ans.

Count the total number of derangements possible for a set of 'N' elements.

  • A derangement is a permutation where no element appears in its original position.

  • Use the formula for derangements: !n = n! * (1 - 1/1! + 1/2! - 1/3! + ... + (-1)^n/n!).

  • Return the answer modulo (10^9 + 7) as the result could be very large.

Add your answer
right arrow

Q34. Mike and Mobile Keypad Problem

Mike, a young math enthusiast, is playing with his mom’s mobile phone, which has a keypad with 12 buttons (10 digits: 0-9, and 2 special characters: ‘*’ and ‘#’). His challenge is...read more

Ans.

Calculate the number of distinct numbers that can be formed by pressing 'N' buttons on a mobile keypad following specific rules.

  • Use dynamic programming to keep track of the number of distinct numbers that can be formed at each step.

  • Consider the possible transitions from each button to calculate the total number of distinct numbers.

  • Implement a solution that efficiently handles large values by using modulo arithmetic.

  • Ensure that the solution runs within the given time limit of ...read more

Add your answer
right arrow

Q35. Strongly Connected Components (Tarjan’s Algorithm) Problem Statement

Given an unweighted directed graph with V vertices and E edges, your task is to identify and print all the strongly connected components (SCC...read more

Ans.

Tarjan's Algorithm is used to find strongly connected components in an unweighted directed graph.

  • Tarjan's Algorithm is a depth-first search based algorithm.

  • It uses a stack to keep track of vertices in the current SCC.

  • The algorithm assigns a unique id to each vertex and keeps track of the lowest id reachable from the current vertex.

  • Once a SCC is identified, the vertices in the stack form that SCC.

  • The algorithm runs in O(V + E) time complexity.

  • Example: For the input graph with ...read more

Add your answer
right arrow

Q36. Sort 0s, 1s, and 2s Problem Statement

You are provided with an integer array/list ARR of size 'N' which consists solely of 0s, 1s, and 2s. Your task is to write a solution to sort this array/list.

Input:

The fi...read more
Ans.

Sort an array of 0s, 1s, and 2s in linear time with a single scan approach.

  • Use three pointers to keep track of the positions of 0s, 1s, and 2s in the array.

  • Iterate through the array once and swap elements based on their values and the pointers.

  • After the single scan, the array will be sorted in the required order.

Add your answer
right arrow

Q37. Sort 0 1 2 Problem Statement

Given an integer array arr of size 'N' containing only 0s, 1s, and 2s, write an algorithm to sort the array.

Input:

The first line contains an integer 'T' representing the number of...read more
Ans.

Sort an array of 0s, 1s, and 2s in linear time complexity.

  • Use three pointers to keep track of 0s, 1s, and 2s while traversing the array.

  • Swap elements based on the values encountered to sort the array in a single scan.

  • Final array will have 0s on the left, 1s in the middle, and 2s on the right.

Add your answer
right arrow

Q38. Shortest Path in a Binary Matrix Problem Statement

Given a binary matrix of size N * M where each element is either 0 or 1, find the shortest path from a source cell to a destination cell, consisting only of 1s...read more

Ans.

Find the shortest path in a binary matrix from a source cell to a destination cell consisting only of 1s.

  • Use Breadth First Search (BFS) algorithm to find the shortest path in the binary matrix.

  • Keep track of visited cells to avoid revisiting them.

  • Update the path length as you traverse the matrix.

  • Return -1 if no valid path exists from source to destination.

Add your answer
right arrow

Q39. Maximum 0-1 Distance Problem Statement

Given a binary matrix of size N*M, find the maximum distance 'di' for every 0-cell to its nearest 1-cell, where the distance is measured using Manhattan distance. The task...read more

Ans.

Find the maximum Manhattan distance from a 0-cell to its nearest 1-cell in a binary matrix.

  • Iterate through the matrix to find all 0-cells and calculate their distances to nearest 1-cells using Manhattan distance formula

  • Keep track of the maximum distance found so far and update it if a larger distance is encountered

  • Return the maximum distance as the final result

Add your answer
right arrow

Q40. Special Binary Tree Problem Statement

Determine whether an arbitrary binary tree is special. A binary tree is called special if every node in this tree has either zero or two children.

Example:

Input:
3
5 1
6 2 0...read more
Ans.

Determine if a binary tree is special if every node has zero or two children.

  • Traverse the tree and check if each node has either 0 or 2 children.

  • Use a recursive approach to check children of each node.

  • If any node has only one child, return false immediately.

  • Example: For the given input, the output should be true.

Add your answer
right arrow

Q41. Pair Sum Problem Statement

You are given an integer array 'ARR' of size 'N' and an integer 'S'. Your task is to find and return a list of all pairs of elements where each sum of a pair equals 'S'.

Note:

Each pa...read more

Ans.

Given an array and a target sum, find all pairs of elements in the array that add up to the target sum.

  • Create an empty list to store the pairs

  • Iterate through the array and for each element, check if there is a complement (target sum minus the current element) in the array

  • If a complement is found, add the pair (current element, complement) to the list

  • Sort the list of pairs in non-decreasing order of their first value

  • If two pairs have the same first value, sort them based on th...read more

Add your answer
right arrow

Q42. Frequency in a Sorted Array Problem Statement

Given a sorted array ARR and a number X, your task is to determine the count of occurrences of X within ARR.

Note:

  • If X is not found in the array, return 0.
  • The ar...read more
Ans.

The task is to count the number of occurrences of a given number in a sorted array.

  • Use binary search to find the first and last occurrence of the given number in the array.

  • Subtract the indices of the first and last occurrence to get the count.

  • Handle the case when the number is not found in the array.

Add your answer
right arrow

Q43. Postfix Expression Evaluation Problem Statement

Given a postfix expression, your task is to evaluate the expression. The operator will appear in the expression after the operands. The output for each expression...read more

Ans.

Evaluate postfix expressions by applying operators after operands. Return result modulo (10^9+7).

  • Iterate through each character in the postfix expression

  • If character is an operand, push it onto the stack

  • If character is an operator, pop two operands from stack, apply operator, and push result back

  • Continue until end of expression, return final result modulo (10^9+7)

Add your answer
right arrow

Q44. 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

Ans.

Connect ropes with minimum cost by merging the smallest ropes first.

  • Sort the array of rope lengths in ascending order.

  • Merge the two smallest ropes at each step to minimize cost.

  • Keep track of the total cost as you merge the ropes.

  • Repeat until all ropes are merged into one.

  • Return the total cost as the minimum cost to connect all ropes.

Add your answer
right arrow

Q45. Minimum Window Subsequence Problem Statement

You are given two strings S and T. Your task is to determine the smallest contiguous substring W of S, such that T is a subsequence of W.

A subsequence is a sequence...read more

Ans.

Find the smallest contiguous substring of S containing T as a subsequence.

  • Use dynamic programming to find the minimum length substring.

  • Iterate through S and T to find the minimum length substring.

  • Keep track of the indices of the characters in S that match with T.

Add your answer
right arrow

Q46. Difference between online and offline shopping.

Ans.

Online shopping allows for convenience and a wider selection, while offline shopping offers a more tactile and personal experience.

  • Online shopping can be done from anywhere with an internet connection

  • Offline shopping allows customers to physically see and touch products before purchasing

  • Online shopping often offers a wider selection of products and better prices

  • Offline shopping can provide a more personalized experience with knowledgeable staff and in-store events

  • Examples of ...read more

View 181 more answers
right arrow

Q47. What is the good quality of a sales man?

Ans.

A good quality of a salesperson is their ability to listen and understand the customer's needs.

  • Active listening skills

  • Empathy towards customers

  • Ability to understand customer's pain points

  • Effective communication skills

  • Ability to build rapport with customers

  • Persistence and resilience

  • Product knowledge

  • Ability to close deals

View 33 more answers
right arrow

Q48. Kth Smallest and Largest Element Problem Statement

You are provided with an array 'Arr' containing 'N' distinct integers and a positive integer 'K'. Your task is to find the Kth smallest and Kth largest element...read more

Ans.

Find the Kth smallest and largest elements in an array.

  • Sort the array and return the Kth element for smallest and (N-K+1)th element for largest.

  • Use a priority queue to efficiently find the Kth smallest and largest elements.

  • Handle edge cases where K is equal to 1 or N.

Add your answer
right arrow

Q49. Longest Increasing Subsequence Problem Statement

Given an array of integers with 'N' elements, determine the length of the longest subsequence where each element is greater than the previous element. This subse...read more

Ans.

The task is to find the length of the longest increasing subsequence in a given array.

  • Iterate through the array and keep track of the longest increasing subsequence length at each index.

  • Use dynamic programming to store the lengths of increasing subsequences ending at each index.

  • Return the maximum length from the dynamic programming array.

Add your answer
right arrow

Q50. Stack with getMin Operation

Create a stack data structure that supports not only the usual push and pop operations but also getMin(), which retrieves the minimum element, all in O(1) time complexity without usi...read more

Ans.

Implement a stack with push, pop, top, isEmpty, and getMin operations in O(1) time complexity without using extra space for storing additional stack data structures.

  • Use two stacks - one to store the actual elements and another to store the minimum element at each level.

  • When pushing an element, compare it with the current minimum and update the minimum stack accordingly.

  • For getMin operation, simply return the top element of the minimum stack.

  • Ensure all operations like push, po...read more

Add your answer
right arrow

Q51. Sliding Window Maximum Problem Statement

You are given an array/list of integers with length 'N'. A sliding window of size 'K' moves from the start to the end of the array. For each of the 'N'-'K'+1 possible wi...read more

Ans.

Sliding window maximum problem where we find maximum element in each window of size K.

  • Use a deque to store indices of elements in decreasing order within the window.

  • Pop elements from the deque that are out of the current window.

  • Add the maximum element to the result for each window.

Add your answer
right arrow

Q52. First and Last Position of an Element in a Sorted Array

Given a sorted array/list ARR consisting of ‘N’ elements, and an integer ‘K’, your task is to find the first and last occurrence of ‘K’ in ARR.

Explanatio...read more

Ans.

Find the first and last occurrence of an element in a sorted array.

  • Use binary search to find the first occurrence of the element.

  • Use binary search to find the last occurrence of the element.

  • Handle cases where the element is not present in the array.

Add your answer
right arrow

Q53. Character Frequency Problem Statement

You are given a string 'S' of length 'N'. Your task is to find the frequency of each character from 'a' to 'z' in the string.

Example:

Input:
S : abcdg
Output:
1 1 1 1 0 0 ...read more
Ans.

The task is to find the frequency of each character from 'a' to 'z' in a given string.

  • Create an array of size 26 to store the frequency of each character from 'a' to 'z'.

  • Iterate through the string and increment the count of the corresponding character in the array.

  • Print the array of frequencies as the output.

Add your answer
right arrow

Q54. Word Presence in Sentence

Determine if a given word 'W' is present in the sentence 'S' as a complete word. The word should not merely be a substring of another word.

Input:

The first line contains an integer 'T...read more
Ans.

Check if a given word is present in a sentence as a complete word.

  • Split the sentence into words using spaces as delimiter.

  • Check if the given word matches any of the words in the sentence.

  • Ensure that the word is not just a substring of another word in the sentence.

Add your answer
right arrow

Q55. LRU Cache Design Question

Design a data structure for a Least Recently Used (LRU) cache that supports the following operations:

1. get(key) - Return the value of the key if it exists in the cache; otherwise, re...read more

Ans.

Design a Least Recently Used (LRU) cache data structure that supports get and put operations with capacity constraint.

  • Use a combination of hashmap and doubly linked list to implement the LRU cache.

  • Keep track of the least recently used item and update it accordingly.

  • Ensure to handle cache capacity by evicting the least recently used item when the cache is full.

Add your answer
right arrow

Q56. Shortest Path in a Binary Maze

Find the length of the shortest path in a binary maze given in the form of a rectangular matrix of size M*N, where each element is 0 or 1. Calculate the shortest path from a desig...read more

Ans.

Find the length of the shortest path in a binary maze from source to destination.

  • Use BFS algorithm to find the shortest path in the binary maze.

  • Create a visited matrix to keep track of visited cells.

  • Check for valid movements in all four directions.

  • Return the shortest path length or -1 if no path exists.

  • Example: For the given input, the shortest path length is 5.

Add your answer
right arrow

Q57. Inversion Count Problem

Given an integer array ARR of size N with all distinct values, determine the total number of 'Inversions' that exist.

Explanation:

An inversion is a pair of indices (i, j) such that:

  • AR...read more
Ans.

Count the total number of inversions in an integer array.

  • Use a modified merge sort algorithm to count the inversions.

  • Keep track of the count of inversions while merging the subarrays.

  • The time complexity of the solution should be O(n log n).

Add your answer
right arrow

Q58. Minimum Travel Cost Problem

You are given a country called 'Ninjaland' with 'N' states, numbered from 1 to 'N'. These states are connected by 'M' bidirectional roads, each with a specified travel cost. The aim ...read more

Ans.

The task is to select 'N' - 1 roads in a country with 'N' states, such that the tourist bus can travel to every state at least once at minimum cost.

  • The problem can be solved using a minimum spanning tree algorithm, such as Kruskal's algorithm or Prim's algorithm.

  • Create a graph representation of the country using the given roads and their costs.

  • Apply the minimum spanning tree algorithm to find the minimum cost roads that connect all the states.

  • Print the selected roads and thei...read more

Add your answer
right arrow

Q59. Longest Decreasing Subsequence Problem Statement

Given an array/list of integers ARR consisting of N integers, your task is to determine the length of the longest decreasing subsequence.

Explanation:

A subseque...read more

Ans.

Find the length of the longest decreasing subsequence in an array of integers.

  • Use dynamic programming to keep track of the length of the longest decreasing subsequence ending at each index.

  • Initialize an array to store the length of the longest decreasing subsequence for each element.

  • Iterate through the array and update the length of the longest decreasing subsequence for each element based on previous elements.

  • Return the maximum length of the longest decreasing subsequence fo...read more

Add your answer
right arrow

Q60. Covid Vaccination Distribution Problem

As the Government ramps up vaccination drives to combat the second wave of Covid-19, you are tasked with helping plan an effective vaccination schedule. Your goal is to ma...read more

Ans.

Given constraints and rules, find maximum vaccines administered on a specific day during a vaccination drive.

  • Iterate through each test case and calculate the maximum number of vaccines distributed on the specified day.

  • Distribute vaccines evenly across days while maximizing the number on the specified day.

  • Ensure that the sum of vaccines distributed does not exceed the maximum allowed.

  • Consider edge cases like when the number of days is equal to the maximum number of vaccines av...read more

Add your answer
right arrow

Q61. Binary Strings Without Consecutive 1s Problem Statement

Given an integer K, your task is to generate all binary strings of length K such that there are no consecutive 1s in the string.

This means the binary str...read more

Ans.

Generate all binary strings of length K without consecutive 1s in lexicographically increasing order.

  • Use backtracking to generate all possible binary strings without consecutive 1s.

  • Start with an empty string and recursively add '0' or '1' based on the condition of no consecutive 1s.

  • Keep track of the current string and its length to check for consecutive 1s.

  • Return the generated binary strings in lexicographically increasing order.

Add your answer
right arrow

Q62. Path In A Tree Problem Statement

Given a binary tree with 'N' nodes and a specific node 'X', your goal is to print the path from the root node to the specified node 'X'.

Explanation:

A binary tree is a hierarch...read more

Ans.

Given a binary tree and a target node, find the path from the root to the target node.

  • Traverse the binary tree from the root to the target node using depth-first search (DFS).

  • Store the path from the root to the target node while traversing the tree.

  • Print the stored path as the output for each test case.

  • Ensure uniqueness of node values and that the target node exists in the tree.

Add your answer
right arrow

Q63. Maximum Consecutive Ones Problem Statement

Given a binary array 'ARR' of size 'N', your task is to determine the maximum length of a sequence consisting solely of 1’s that can be obtained by converting at most ...read more

Ans.

The task is to find the maximum length of a sequence of 1's by converting at most K zeroes into ones in a binary array.

  • Iterate through the array and keep track of the current window of 1's and zeroes.

  • Use a sliding window approach to find the maximum length of consecutive 1's by flipping at most K zeroes.

  • Update the window based on the number of zeroes flipped and keep track of the maximum length found so far.

  • Return the maximum length of consecutive 1's obtained.

Add your answer
right arrow

Q64. Dijkstra's Shortest Path Problem Statement

Given an undirected graph with V vertices (labeled 0, 1, ..., V-1) and E edges, each edge connects two nodes X and Y with a specified weight representing the distance ...read more

Ans.

Dijkstra's algorithm is used to find the shortest path distance from a source node to all other nodes in an undirected graph.

  • Implement Dijkstra's algorithm to find the shortest path distance from node 0 to all other nodes in the graph.

  • Use a priority queue to efficiently select the next node with the shortest distance.

  • Initialize distances to all nodes as infinity, except for the source node which is 0.

  • Update distances to neighboring nodes if a shorter path is found, and contin...read more

Add your answer
right arrow

Q65. Sum of Big Integers Problem Statement

Given two integers represented as strings, 'NUM1' and 'NUM2', compute and return their sum.

Input:

T
NUM1 NUM2
...

Output:

Sum of NUM1 and NUM2 for each test case

Example:

In...read more
Ans.

Program to compute sum of big integers represented as strings.

  • Convert strings to integers and add them digit by digit from right to left, considering carry over.

  • Handle cases where one number is longer than the other by padding with zeros.

  • Return the final sum as a string.

View 1 answer
right arrow

Q66. Valid Sudoku Problem Statement

You are given a 9 X 9 2D matrix named MATRIX which contains some cells filled with digits (1 to 9) and some cells left empty (denoted by 0).

Your task is to determine if there is ...read more

Ans.

The task is to determine if a given 9x9 matrix can be filled with digits 1-9 to form a valid Sudoku solution.

  • Iterate through each cell in the matrix.

  • For each empty cell, try filling it with a digit from 1-9 and check if it satisfies the Sudoku conditions.

  • Use helper functions to check if the digit is valid in the current row, column, and sub-matrix.

  • If a valid digit is found, recursively fill the next empty cell.

  • If all cells are filled and the Sudoku conditions are satisfied, r...read more

Add your answer
right arrow

Q67. Search in a Row-wise and Column-wise Sorted Matrix Problem Statement

You are given an N * N matrix of integers where each row and each column is sorted in increasing order. Your task is to find the position of ...read more

Ans.

Software testing is the process of evaluating a software item to detect differences between given input and expected output.

  • Software testing ensures that the software is working as expected

  • It helps to identify defects and errors in the software

  • Testing can be done manually or using automated tools

  • Types of testing include functional, performance, security, and usability testing

View 1 answer
right arrow

Q68. Flip Bits Problem Explanation

Given an array of integers ARR of size N, consisting of 0s and 1s, you need to select a sub-array and flip its bits. Your task is to return the maximum count of 1s that can be obta...read more

Ans.

Given an array of 0s and 1s, find the maximum count of 1s by flipping a sub-array at most once.

  • Iterate through the array and keep track of the maximum count of 1s obtained by flipping a sub-array.

  • Consider flipping a sub-array only when it results in increasing the count of 1s.

  • Update the maximum count of 1s as you iterate through the array.

  • Return the maximum count of 1s obtained after considering all possible sub-arrays.

Add your answer
right arrow

Q69. Unique Paths Problem Statement

Given the dimensions of an M x N matrix, determine the total number of unique paths from the top-left corner to the bottom-right corner of the matrix.

Allowed moves are only to th...read more

Ans.

The problem involves finding the total number of unique paths from the top-left corner to the bottom-right corner of an M x N matrix by moving only right or down.

  • Use dynamic programming to solve this problem efficiently.

  • Create a 2D array to store the number of unique paths for each cell in the matrix.

  • Initialize the first row and first column with 1 as there is only one way to reach each cell in those rows and columns.

  • For each cell (i, j), the number of unique paths is the sum...read more

Add your answer
right arrow

Q70. Longest Palindromic Substring Problem Statement

You are provided with a string STR of length N. The goal is to identify the longest palindromic substring within this string. In cases where multiple palindromic ...read more

Ans.

Identify the longest palindromic substring in a given string.

  • Iterate through the string and expand around each character to find palindromes

  • Keep track of the longest palindrome found so far

  • Return the longest palindromic substring with the smallest start index

Add your answer
right arrow

Q71. Next Greater Element Problem Statement

You are provided with an array or list ARR containing N positive integers. Your task is to determine the Next Greater Element (NGE) for each element in the array.

The Next...read more

Ans.

Find the Next Greater Element for each element in an array.

  • Iterate through the array from right to left and use a stack to keep track of elements.

  • Pop elements from the stack until a greater element is found or the stack is empty.

  • Store the next greater element for each element in a result array.

Add your answer
right arrow

Q72. Trapping Rainwater Problem Statement

You are given an array ARR of long type, which represents an elevation map where ARR[i] denotes the elevation of the ith bar. Calculate the total amount of rainwater that ca...read more

Ans.

Calculate the total amount of rainwater that can be trapped within given elevation map.

  • Iterate through the array to find the maximum height on the left and right of each bar.

  • Calculate the amount of water that can be trapped above each bar by taking the minimum of the maximum heights on the left and right.

  • Sum up the trapped water above each bar to get the total trapped water for the elevation map.

Add your answer
right arrow

Q73. Find Row K Problem Explanation

You are given a square binary matrix mat[n][n]. The task is to determine an integer 'K' such that:

  • All elements in the Kth row are 0.
  • All elements in the Kth column are 1.

The v...read more

Ans.

Find the row and column in a binary matrix where all elements in the row are 0 and all elements in the column are 1.

  • Iterate through each row and column to check for the conditions mentioned in the problem statement.

  • If a row has all 0s and the corresponding column has all 1s, return the index of that row/column.

  • If no such row/column exists, return -1.

Add your answer
right arrow

Q74. Infix to Postfix Conversion

You are provided with a string EXP which represents a valid infix expression. Your task is to convert this given infix expression into a postfix expression.

Explanation:

An infix exp...read more

Ans.

Convert infix expression to postfix expression.

  • Use a stack to keep track of operators and operands.

  • Follow the rules of precedence for operators.

  • Handle parentheses by pushing them onto the stack.

  • Process the expression from left to right to convert to postfix form.

Add your answer
right arrow

Q75. What are the different types of hashing? Suggest an alternative and a better way for Linear Chaining.

Ans.

Different types of hashing and alternative for Linear Chaining

  • Different types of hashing include division, multiplication, and universal hashing

  • Alternative for Linear Chaining is Open Addressing

  • Open Addressing includes Linear Probing, Quadratic Probing, and Double Hashing

View 2 more answers
right arrow

Q76. 14. you have given a string of multiline. you have to print the maximum occupancy word in each line and if there is some capital letter in each line then print each capital letter occupancy and then small lette...

read more
Ans.

The question asks to find the maximum occupancy word in each line of a given multiline string and also count the occupancy of capital and small letters separately.

  • Split the multiline string into individual lines

  • For each line, split it into words

  • Initialize variables to store the maximum occupancy word and its count

  • Iterate through each word and count the occupancy of each letter

  • If the current word has a higher occupancy than the maximum occupancy word, update the maximum occupa...read more

View 1 answer
right arrow

Q77. Closest Sum Problem Statement

Given an array of integers ARR of size N and an integer target, find three integers in ARR such that their sum is closest to the target. If there are two closest sums, return the s...read more

Ans.

The task is to find three integers in an array whose sum is closest to a given target.

  • Iterate through all possible triplets in the array to find the closest sum to the target.

  • Keep track of the closest sum found so far and update it if a closer sum is found.

  • Return the closest sum found after iterating through all triplets.

View 1 answer
right arrow

Q78. Longest Common Prefix Problem Statement

You are given an array ‘ARR’ consisting of ‘N’ strings. Your task is to find the longest common prefix among all these strings. If there is no common prefix, you have to ...read more

Ans.

Find the longest common prefix among an array of strings.

  • Iterate through the characters of the first string and compare with corresponding characters of other strings.

  • Stop when a character doesn't match or reach the end of any string.

  • Return the prefix found so far as the longest common prefix.

View 1 answer
right arrow

Q79. Count Inversions Problem Statement

Given an integer array ARR of size N, your task is to find the total number of inversions that exist in the array.

An inversion is defined for a pair of integers in the array ...read more

Ans.

The task is to count the number of inversions in an array.

  • Iterate through the array and for each element, compare it with all the elements that come after it.

  • If the current element is greater than any of the elements that come after it, increment the inversion count.

  • Return the inversion count as the result.

Add your answer
right arrow

Q80. String Palindrome Verification

Given a string, your task is to determine if it is a palindrome considering only alphanumeric characters.

Input:

The input is a single string without any leading or trailing space...read more
Ans.

Check if a given string is a palindrome considering only alphanumeric characters.

  • Remove non-alphanumeric characters from the input string.

  • Convert the string to lowercase for case-insensitive comparison.

  • Compare characters from start and end of the string to check for palindrome.

  • Return 'true' if the string is a palindrome, 'false' otherwise.

View 1 answer
right arrow

Q81. Most Frequent Word Problem Statement

You are given two strings 'A' and 'B' composed of words separated by spaces. Your task is to determine the most frequent and lexicographically smallest word in string 'A' th...read more

Ans.

Find the most frequent and lexicographically smallest word in string 'A' that is not present in string 'B'.

  • Split strings 'A' and 'B' into words

  • Count frequency of each word in 'A'

  • Check if word is not in 'B' and is the most frequent and lexicographically smallest

  • Return the word or -1 if no such word exists

Add your answer
right arrow

Q82. Simplify Directory Path Problem Statement

You are provided with a directory path in Unix-style notation, and your task is to simplify it according to given rules.

In a Unix-style file system:

  • A dot (.) refers ...read more
Ans.

The task is to simplify a given Unix-style directory path and determine the final destination.

  • Replace multiple slashes with a single slash

  • Handle dot (.) by ignoring it

  • Handle double dot (..) by removing the previous directory from the path

  • Ensure the simplified path starts with a slash and does not have a trailing slash

Add your answer
right arrow

Q83. Missing Number in Concatenated Sequence

You were given a sequence of consecutive nonnegative integers but missed one while appending them to create a string S. Your task is to identify the missing integer from ...read more

Ans.

The task is to find the missing number in a string of consecutive nonnegative integers.

  • Iterate through the string and check if each substring can form a valid number

  • If a substring forms a valid number, check if it is consecutive with the previous number

  • If a substring does not form a valid number or is not consecutive, it is the missing number

  • Handle edge cases such as multiple missing numbers or all numbers already present

Add your answer
right arrow

Q84. Unique Element in Array

Given an arbitrary array arr consisting of N non-negative integers where every element appears thrice except for one. Your task is to find the element in the array that appears only once...read more

Ans.

Find the unique element in an array where every element appears thrice except for one.

  • Use XOR operation to find the unique element.

  • Iterate through the array and XOR each element to find the unique element.

  • The XOR operation cancels out elements that appear thrice, leaving only the unique element.

  • Example: arr = [2, 2, 3, 2], XOR of all elements = 3.

  • Example: arr = [0, 1, 0, 1, 0, 1, 99], XOR of all elements = 99.

Add your answer
right arrow

Q85. Number with Maximum Probability Problem Statement

In this game, players Ninja Misha and Ninja Andrew each choose an integer within the range of 1 to 'N'. After their choices, a random integer 'C' is drawn from ...read more

Ans.

Find the optimal number for Andrew to choose to maximize his winning probability in a game against Misha.

  • Andrew should choose the number equidistant from Misha's number and the random integer C to maximize his winning probability.

  • The optimal number for Andrew to choose is the average of Misha's number and C, rounded up if the average is not an integer.

  • If the average of Misha's number and C is an integer, Andrew should choose that number or the next highest integer if it excee...read more

Add your answer
right arrow

Q86. 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

Ans.

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

Add your answer
right arrow

Q87. 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

Ans.

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.

Add your answer
right arrow

Q88. 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

Ans.

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.

Add your answer
right arrow

Q89. Reverse Doubly Linked List Nodes in Groups

You are given a doubly linked list of integers along with a positive integer K that represents the group size. Your task is to modify the linked list by reversing ever...read more

Ans.

Reverse groups of K nodes in a doubly linked list

  • Iterate through the linked list in groups of K nodes

  • Reverse each group of K nodes

  • Handle the case where the number of nodes left is less than K

Add your answer
right arrow

Q90. Triplets in a Sorted Doubly Linked List

Given a sorted doubly linked list of distinct nodes, determine how many triplets in the list have a sum equal to a given value 'X'. Each node in the list contains a uniqu...read more

Ans.

Given a sorted doubly linked list of distinct nodes, find and count triplets with a sum equal to a given value 'X'.

  • Iterate through the list and for each node, use two pointers to find the other two nodes that sum up to 'X'.

  • Keep track of the count of triplets found and return it at the end.

  • Handle edge cases like when the list has less than 3 nodes or no triplets are found.

Add your answer
right arrow

Q91. Minimum Jumps Problem Statement

Bob and his wife are in the famous 'Arcade' mall in the city of Berland. This mall has a unique way of moving between shops using trampolines. Each shop is laid out in a straight...read more

Ans.

Find the minimum number of jumps Bob needs to make from shop 0 to reach the final shop, or return -1 if impossible.

  • Use Breadth First Search (BFS) to find the minimum number of jumps needed.

  • Keep track of the maximum reachable index at each step.

  • If the maximum reachable index is less than the current index, return -1 as it's impossible to reach the last shop.

Add your answer
right arrow

Q92. Minimum Cost to Connect All Points Problem Statement

You are provided with an array, coordinates, which represents integer coordinates of several points on a 2D plane. The task is to determine the minimum cost ...read more

Ans.

Calculate the minimum cost to connect all points on a 2D plane using Manhattan distance.

  • Calculate Manhattan distance between each pair of points

  • Use a minimum spanning tree algorithm like Kruskal's or Prim's to find the minimum cost

  • Sum up the distances in the minimum spanning tree to get the minimum cost

Add your answer
right arrow

Q93. Right View of Binary Tree Problem Statement

Given a Binary Tree of integers, your task is to compute and print the right view of it.

The right view of a Binary Tree is a set of nodes visible when the tree is vi...read more

Ans.

The task is to compute and print the right view of a Binary Tree when viewed from the right side.

  • Traverse the tree level by level and keep track of the rightmost node at each level.

  • Print the rightmost node of each level to get the right view of the Binary Tree.

  • Use a queue data structure for level-order traversal of the Binary Tree.

Add your answer
right arrow

Q94. Min Stack Problem Statement

Design a special stack that supports the following operations in constant time:

  1. Push(num): Insert the given number into the stack.
  2. Pop: Remove and return the top element from the st...read more
Ans.

Design a special stack supporting constant time operations like push, pop, top, and getMin.

  • Use an additional stack to keep track of the minimum element at each level.

  • When pushing a new element, compare it with the top of the minimum stack to update the minimum.

  • Ensure constant time complexity for all operations by maintaining the minimum stack.

  • Example: Push(1), Push(2), getMin() should return 1.

Add your answer
right arrow

Q95. Minimum Direction Changes Problem Statement

You are given a 2D grid with N rows and M columns. Each cell in the grid has a character from the set { 'U', 'L', 'D', 'R' } indicating the allowable move direction: ...read more

Ans.

Find the minimum number of direction changes required to reach the bottom-right cell in a grid by following cell directions.

  • Iterate through the grid cells and keep track of the direction changes needed to reach each cell.

  • Use dynamic programming to calculate the minimum direction changes from top-left to bottom-right cell.

  • Consider the possible directions at each cell and choose the one with minimum direction changes.

  • Return the minimum number of direction changes needed to reac...read more

Add your answer
right arrow

Q96. Smallest Window Problem Statement

Given two strings S and X containing random characters, the task is to find the smallest substring in S which contains all the characters present in X.

Input:

The first line co...read more
Ans.

Find the smallest substring in S containing all characters in X.

  • Use a sliding window approach to find the smallest window in S containing all characters in X.

  • Keep track of the characters in X using a hashmap.

  • Move the window to the right until all characters in X are found, then shrink the window from the left to find the smallest window.

  • Return the smallest window found.

  • Example: S = 'abdd', X = 'bd' -> Output: 'bd'

Add your answer
right arrow

Q97. Anagram Pairs Verification Problem

Your task is to determine if two given strings are anagrams of each other. Two strings are considered anagrams if you can rearrange the letters of one string to form the other...read more

Ans.

The task is to determine whether two given strings form an anagram pair or not.

  • Anagrams are words or names that can be formed by rearranging the letters of another word

  • Check if the two strings have the same characters with the same frequency

  • Convert the strings to character arrays and sort them

  • Compare the sorted arrays to check if they are equal

Add your answer
right arrow

Q98. 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
Ans.

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

Add your answer
right arrow

Q99. Next Smallest Palindrome Problem Statement

Find the next smallest palindrome strictly greater than a given number 'N' represented as a string 'S'.

Explanation:

You are given a number in string format, and your ...read more

Ans.

Find the next smallest palindrome greater than a given number represented as a string.

  • Convert the string to an integer, find the next greater palindrome, and convert it back to a string.

  • Handle cases where the number is a palindrome or has all digits as '9'.

  • Consider both odd and even length numbers when finding the next palindrome.

Add your answer
right arrow

Q100. Dice Throws Problem Statement

You are given D dice, each having F faces numbered from 1 to F. The task is to determine the number of possible ways to roll all the dice such that the sum of the face-up numbers e...read more

Ans.

The task is to determine the number of possible ways to roll all the dice such that the sum of the face-up numbers equals the given 'target' sum.

  • Use dynamic programming to solve the problem efficiently.

  • Create a 2D array to store the number of ways to achieve each sum with different number of dice.

  • Iterate through the dice and sum possibilities to fill up the array.

  • Return the result modulo 10^9 + 7.

  • Optimize the solution to use no more than O(S) extra space by using rolling arra...read more

Add your answer
right arrow
1
2
3
4
5
6
7
Next

More about working at Amazon

Back
Awards Leaf
AmbitionBox Logo
Top Rated Mega Company - 2024
Awards Leaf
Awards Leaf
AmbitionBox Logo
Top Rated Company for Women - 2024
Awards Leaf
Awards Leaf
AmbitionBox Logo
Top Rated Internet/Product Company - 2024
Awards Leaf
Contribute & help others!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos

Interview Process at Amazon

based on 4.1k interviews
Interview experience
4.3
Good
View more
interview tips and stories logo
Interview Tips & Stories
Ace your next interview with expert advice and inspiring stories

Top Interview Questions from Similar Companies

Samsung Logo
3.9
 • 396 Interview Questions
UltraTech Cement Logo
4.2
 • 330 Interview Questions
Aarti Industries Logo
4.1
 • 221 Interview Questions
Info Edge Logo
3.9
 • 198 Interview Questions
HDFC Life Logo
4.0
 • 173 Interview Questions
View all
Recently Viewed
DESIGNATION
Pyspark Developer
25 interviews
AWARDS
ABECA 2024
AmbitionBox Employee Choice Awards
REVIEWS
Amazon
No Reviews
REVIEWS
Jio
No Reviews
REVIEWS
Mahanagar Telephone Nigam
No Reviews
JOBS
Amazon
No Jobs
REVIEWS
Mphasis
No Reviews
REVIEWS
Amazon
No Reviews
SALARIES
Jio
SALARIES
Mphasis
Top Amazon Interview Questions And Answers
Share an Interview
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
70 Lakh+

Reviews

5 Lakh+

Interviews

4 Crore+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter