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
Clear (1)

500+ Amazon Interview Questions and Answers for Freshers

Updated 1 Mar 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. 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

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

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

Q6. 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
Are these interview questions helpful?

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

Q8. 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
Share interview questions and help millions of jobseekers 🌟
man with laptop

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Q28. Minimum Number of Swaps to Sort an Array

Find the minimum number of swaps required to sort a given array of distinct elements in ascending order.

Input:

T (number of test cases)
For each test case:
N (size of the...read more
Ans.

The minimum number of swaps required to sort a given array of distinct elements in ascending order.

  • Use graph theory and cycle detection to find the minimum number of swaps

  • Count the number of cycles in the permutation

  • Each cycle requires (cycle_length - 1) swaps to sort

Add your answer
right arrow

Q29. Weighted Job Scheduling Problem Statement

You have 'N' jobs, each with a start time, end time, and profit. Your task is to identify the maximum profit that can be earned by scheduling these jobs such that no tw...read more

Ans.

The Weighted Job Scheduling problem involves maximizing profit by scheduling non-overlapping jobs with start time, end time, and profit given.

  • Sort the jobs based on their end times in ascending order.

  • Use dynamic programming to keep track of the maximum profit that can be earned by including or excluding each job.

  • For each job, find the maximum profit that can be earned by including it and excluding it.

  • Choose the maximum profit from the two options for each job.

  • Repeat the proce...read more

Add your answer
right arrow

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

Q31. Reverse Doubly Linked List in Groups Problem

You are provided with a Doubly Linked List consisting of integers and a positive integer 'K', which represents the size of the group. Your task is to modify the link...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

  • Update the pointers accordingly

  • Handle cases where the number of remaining nodes is less than K

Add your answer
right arrow

Q32. Minimum Number of Platforms Problem

Your task is to determine the minimum number of platforms required at a railway station so that no train has to wait.

Explanation:

Given two arrays:

  • AT - representing the ar...read more
Ans.

Determine the minimum number of platforms needed at a railway station so that no train has to wait.

  • Sort the arrival and departure times arrays in ascending order.

  • Initialize two pointers, one for arrival times and one for departure times.

  • Increment the platform count when a train arrives and decrement when it departs.

  • Keep track of the maximum platform count needed.

  • Return the maximum platform count as the minimum number of platforms needed.

Add your answer
right arrow

Q33. Square Root with Decimal Precision Problem

Your task is to compute the square root of a given integer N, such that the result is as accurate as D decimal places. The aim is to ensure that the absolute differenc...read more

Ans.

Compute square root of integer with specified decimal precision.

  • Implement a function to calculate square root using binary search or Newton's method.

  • Keep track of the precision required and stop when the difference is within the limit.

  • Handle multiple test cases efficiently to meet the time limit.

  • Ensure the output is formatted to the specified decimal places.

  • Consider edge cases like maximum input values and precision requirements.

Add your answer
right arrow

Q34. Maximum Subtree Sum Problem Statement

Given an arbitrary binary tree consisting of N nodes, your task is to find the largest subtree sum.

Input:

First line of each input has a single integer T, denoting the num...read more
Ans.

Find the largest subtree sum in an arbitrary binary tree.

  • Traverse the binary tree to calculate the subtree sum of each node.

  • Keep track of the maximum subtree sum encountered so far.

  • Recursively calculate the subtree sum for each node by considering its left and right children.

  • Consider edge cases like when the tree is empty or has only one node.

Add your answer
right arrow

Q35. Kth Smallest Element in an Unsorted Array

Given an unsorted array arr of distinct integers and an integer k, your task is to find the k-th smallest element in the array.

Input:

The first line of input contains ...read more
Ans.

Find the k-th smallest element in an unsorted array of distinct integers.

  • Sort the array and return the k-th element.

  • Use a min-heap to find the k-th smallest element efficiently.

  • Implement quickselect algorithm to find the k-th smallest element in linear time.

Add your answer
right arrow

Q36. Find Number of Islands

You are provided with a 2-dimensional array/list of size N rows by M columns, containing ones (1) and zeroes (0). Here, 1 represents land, and 0 represents water.

A cell is considered con...read more

Ans.

Find the number of islands in a 2D matrix of 1s and 0s.

  • Iterate through the matrix and perform depth-first search (DFS) to find connected 1s.

  • Use a visited array to keep track of visited cells to avoid counting the same island multiple times.

  • Increment the island count whenever a new island is encountered.

Add your answer
right arrow

Q37. Left View of a Binary Tree

Given a binary tree, your task is to print the left view of the tree. The left view of a binary tree contains the nodes visible when the tree is viewed from the left side.

Input:

The ...read more
Ans.

Print the left view of a binary tree, containing nodes visible from the left side.

  • Traverse the tree level by level and print the first node of each level.

  • Use a queue to keep track of nodes at each level.

  • Handle null nodes represented by -1 in the input.

Add your answer
right arrow

Q38. Minimum Path Sum Problem Statement

Consider a 2-dimensional grid 'GRID' with 'N' rows and 'M' columns in Ninjaland. Each cell in the grid has an associated cost. The goal is to determine the minimum path sum fr...read more

Ans.

The Minimum Path Sum Problem involves finding the minimum sum of costs along a path from the top-left to the bottom-right of a grid.

  • Use dynamic programming to calculate the minimum path sum by considering the costs of moving down or right at each cell.

  • Initialize a 2D array to store the minimum path sum values for each cell in the grid.

  • Iterate through the grid to calculate the minimum path sum for each cell based on the previous cells.

  • Return the minimum path sum for the bottom...read more

Add your answer
right arrow

Q39. Print Nodes at Distance K from a Given Node

Given an arbitrary binary tree, a node of the tree, and an integer 'K', find all nodes that are at a distance K from the specified node, and return a list of these no...read more

Ans.

Given a binary tree, a target node, and an integer K, find all nodes at distance K from the target node.

  • Traverse the binary tree to find the target node.

  • Use BFS to traverse the tree from the target node to nodes at distance K.

  • Keep track of the distance while traversing the tree.

  • Return the values of nodes at distance K in any order.

Add your answer
right arrow

Q40. Loot Houses Problem Statement

A thief is planning to steal from several houses along a street. Each house has a certain amount of money stashed. However, the thief cannot loot two adjacent houses. Determine the...read more

Ans.

Determine the maximum amount of money a thief can steal from houses without looting two consecutive houses.

  • Use dynamic programming to keep track of the maximum amount of money that can be stolen up to each house.

  • At each house, the thief can either choose to steal from the current house and the house two steps back, or skip the current house and steal from the previous house.

  • Return the maximum amount of money that can be stolen at the last house.

Add your answer
right arrow

Q41. Find Missing Number In String Problem Statement

You have a sequence of consecutive nonnegative integers. By appending all integers end-to-end, you formed a string S without any separators. During this process, ...read more

Ans.

Given a string of consecutive nonnegative integers with one missing number, find the missing integer.

  • Iterate through the string and check for missing numbers by comparing adjacent integers

  • Calculate the sum of the original sequence and the sum of the integers in the string to find the missing number

  • Handle cases where there are multiple missing numbers or the string is invalid

Add your answer
right arrow

Q42. Spiral Order Traversal of a Binary Tree

Given a binary tree with N nodes, your task is to output the Spiral Order traversal of the binary tree.

Input:

The input consists of a single line containing elements of ...read more
Ans.

Implement a function to return the spiral order traversal of a binary tree.

  • Traverse the binary tree level by level, alternating between left to right and right to left.

  • Use a queue to keep track of nodes at each level.

  • Append nodes to the result list in the order they are visited.

Add your answer
right arrow

Q43. String Rearrangement Problem Statement

You are given a string of lowercase characters. The objective is to rearrange (reorder) the string so that no two adjacent characters are identical.

Return the rearranged ...read more

Ans.

Given a string of lowercase characters, rearrange it so that no two adjacent characters are identical. Return the rearranged string or 'NO SOLUTION'.

  • Iterate through the string and count the frequency of each character.

  • Sort the characters based on their frequency in non-increasing order.

  • Place the characters with highest frequency first, alternating with other characters.

  • If there are more than half of the characters with the same frequency, 'NO SOLUTION' is returned.

Add your answer
right arrow

Q44. Family Structure Problem Statement

Aakash belongs to a unique family structure where every male member (M) has a male child first followed by a female child, and every female member (F) has a female child first...read more

Ans.

Determine the gender of the Kth child in the Nth generation based on a unique family structure.

  • Every male member has a male child first followed by a female child, and every female member has a female child first followed by a male child.

  • Given generation number N and position of the child K, determine the gender of the Kth child in the Nth generation.

  • Output 'Male' if the child is male, otherwise 'Female'.

  • Start the family tree from the male member, Aakash.

Add your answer
right arrow

Q45. Clone a Linked List with Random Pointers Problem Statement

Given a linked list where each node contains two pointers: the first points to the next node in sequence, and the second is a random pointer that can p...read more

Ans.

Clone a linked list with random pointers by creating deep copy of the original list without duplicating references.

  • Create a deep copy of the linked list by instantiating new nodes for each node in the original list.

  • Ensure that the random pointers in the cloned list point to the corresponding nodes in the new list.

  • Do not duplicate references to original nodes while creating the clone.

  • Implement the function to clone the linked list without using additional space.

  • Verify that the...read more

Add your answer
right arrow

Q46. Largest Rectangle in Histogram Problem Statement

You are given an array/list HEIGHTS of length N, where each element represents the height of a histogram bar. The width of each bar is considered to be 1.

Your t...read more

Ans.

Find the area of the largest rectangle that can be formed within the bounds of a given histogram.

  • Iterate through the histogram bars and maintain a stack to keep track of increasing heights.

  • Calculate the area of the rectangle formed by each bar as the smallest height in the stack times the width.

  • Update the maximum area found so far and return it as the result.

Add your answer
right arrow

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

Q48. Group Anagrams Problem Statement

Given an array or list of strings called inputStr, your task is to return the strings grouped as anagrams. Each group should contain strings that are anagrams of one another.

An...read more

Ans.

Group anagrams in an array of strings based on their characters.

  • Iterate through the array of strings and sort each string to group anagrams together.

  • Use a hashmap to store the sorted string as key and the list of anagrams as value.

  • Return the values of the hashmap as the grouped anagrams.

Add your answer
right arrow

Q49. Is Binary Heap Tree Problem Statement

You are given a binary tree of integers. Your task is to determine if it is a binary heap tree or not.

Input:

The first line of input contains an integer ‘T’ denoting the n...read more
Ans.

Determine if a given binary tree is a binary heap tree or not based on certain properties.

  • Check if the binary tree is a complete binary tree where every level, except the last level, is completely filled and the last level is as far left as possible.

  • Ensure that every parent node is greater than all its children nodes, forming a max-heap.

  • If any node does not have a left or right child, it should be represented as -1 in the input.

Add your answer
right arrow

Q50. Special Binary Tree Verification

Determine whether a given binary tree is 'special'. A binary tree is defined as 'special' if every node either has zero or two children.

Example:

Input:
3
5 1
6 2 0 8
-1 -1 7 4 -1 ...read more
Ans.

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

  • Traverse the binary tree and check if each non-leaf node has exactly two children.

  • Use a recursive approach to check each node's children.

  • Handle NULL nodes represented by -1 in the input.

Add your answer
right arrow

Q51. Optimize Memory Usage Problem Statement

Alex wants to maximize the use of 'K' memory spaces on his computer. He has 'N' different document downloads, each with unique memory usage, and 'M' computer games, each ...read more

Ans.

Maximize memory usage by pairing downloads and games within memory limit 'K'.

  • Sort the downloads and games in descending order.

  • Iterate through the sorted arrays to find the optimal pairs within memory limit 'K'.

  • Return the indices of the selected download and game pairs.

Add your answer
right arrow

Q52. Given 2 integers a and b, the sequence which will be formed is a, b, a+b, a+2b…. i.e Current element = sum of the previous 2 elements. So now given a number k, how to figure out if it lies in the sequence or no...

read more
Ans.

To check if a number k lies in a sequence formed by adding previous 2 elements, start with a=0 and b=1 and iterate until k is found or exceeded.

  • Start with a=0 and b=1

  • Iterate through the sequence until k is found or exceeded

  • If k is found, return true. If exceeded, return false

Add your answer
right arrow

Q53. Duplicate Integer in Array

Given an array ARR of size N, containing each number between 1 and N-1 at least once, identify the single integer that appears twice.

Input:

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

Identify the duplicate integer in an array containing numbers between 1 and N-1.

  • Iterate through the array and keep track of the frequency of each number using a hashmap.

  • Return the number with a frequency greater than 1 as the duplicate integer.

  • Time complexity can be optimized to O(N) using Floyd's Tortoise and Hare algorithm.

  • Example: For input [1, 2, 3, 4, 4], the output should be 4.

Add your answer
right arrow

Q54. Ninja and Binary String Problem Statement

Ninja has a binary string S of size N given by his friend. The task is to determine if it's possible to sort the binary string S in decreasing order by removing any num...read more

Ans.

Determine if a binary string can be sorted in decreasing order by removing non-adjacent characters.

  • Check if the count of '1's in the string is equal to the length of the string, as it can be sorted in decreasing order by removing non-adjacent characters.

  • If the count of '1's is not equal to the length of the string, check if the string can be rearranged to form a decreasing order by removing non-adjacent characters.

  • Consider edge cases like all '0's or all '1's in the string.

Add your answer
right arrow

Q55. Subarray With Given Sum Problem Statement

Given an array ARR of N integers and an integer S, determine if there exists a contiguous subarray within the array with a sum equal to S. If such a subarray exists, re...read more

Ans.

Given an array of integers and a target sum, find a contiguous subarray with the sum equal to the target.

  • Iterate through the array while keeping track of the current sum and start index.

  • Use a hashmap to store the cumulative sum and its corresponding index.

  • If the current sum - target sum exists in the hashmap, a subarray with the target sum is found.

  • Return the start index and current index as the end index of the subarray.

Add your answer
right arrow

Q56. Boundary Traversal of a Binary Tree

Given a binary tree of integers, your task is to return the boundary nodes of the tree in Anti-Clockwise direction starting from the root node.

Input:

The first line contains...read more
Ans.

Return the boundary nodes of a binary tree in Anti-Clockwise direction starting from the root node.

  • Traverse the left boundary nodes in a top-down manner

  • Traverse the leaf nodes from left to right

  • Traverse the right boundary nodes in a bottom-up manner

  • Handle cases where duplicates occur in the boundary nodes

  • Implement the function without printing as printing is already managed

Add your answer
right arrow

Q57. K Most Frequent Words Problem Statement

Given an array or list WORDS of 'N' non-empty words and an integer 'K', identify the 'K' most frequent words and return them sorted by their frequency, in descending orde...read more

Ans.

Identify the K most frequent words in a list, sorted by frequency and lexicographical order.

  • Use a hashmap to store word frequencies

  • Use a min heap to keep track of K most frequent words

  • Sort the heap based on frequency and lexicographical order

Add your answer
right arrow

Q58. K Closest Points to Origin Problem Statement

Your house is located at the origin (0,0) of a 2-D plane. There are N neighbors living at different points on the plane. Your goal is to visit exactly K neighbors wh...read more

Ans.

Find the K closest points to the origin in a 2-D plane using Euclidean Distance.

  • Calculate the Euclidean Distance of each point from the origin

  • Sort the points based on their distances from the origin

  • Return the first K points as the closest points

Add your answer
right arrow

Q59. LCA of Binary Tree Problem Statement

You are given a binary tree consisting of distinct integers and two nodes, X and Y. Your task is to find and return the Lowest Common Ancestor (LCA) of these two nodes.

The ...read more

Ans.

Find the Lowest Common Ancestor (LCA) of two nodes in a binary tree.

  • Traverse the binary tree to find the paths from the root to nodes X and Y.

  • Compare the paths to find the last common node, which is the LCA.

  • Handle cases where one node is an ancestor of the other.

  • Consider edge cases like when X or Y is the root node.

  • Implement a recursive or iterative solution to find the LCA efficiently.

Add your answer
right arrow

Q60. Ninja and Binary Tree Challenge

Implement a binary tree class from scratch. You are required to handle three types of queries on the binary tree:

  • ‘I’ ‘VAL’: Insert a node with value 'VAL' into the binary tree....read more
Ans.

Implement a binary tree class from scratch to handle insert, delete, and random retrieval queries.

  • Create a binary tree class with insert and delete methods.

  • Implement a method to randomly retrieve a node from the tree.

  • Ensure equal chance of selection for each node during random retrieval.

  • Handle different types of queries ('I', 'D', 'R') on the binary tree.

  • Return the value of the randomly chosen node for each test case.

Add your answer
right arrow

Q61. Bridge in Graph Problem Statement

Given an undirected graph with V vertices and E edges, your task is to find all the bridges in this graph. A bridge is an edge that, when removed, increases the number of conne...read more

Ans.

Find all the bridges in an undirected graph.

  • Use Tarjan's algorithm to find bridges in the graph.

  • A bridge is an edge whose removal increases the number of connected components.

  • Check for bridges by removing each edge and checking the number of connected components.

  • Return the edges that are bridges in non-decreasing order.

Add your answer
right arrow

Q62. Mean, Median, and Mode Problem Statement

Given an integer array ARR of size N, you need to compute the following three statistical measures:

  1. Mean: Implement the function mean() to calculate the mean of the arr...read more
Ans.

Implement functions to calculate mean, median, and mode of an integer array.

  • Calculate mean by summing all elements and dividing by total count

  • Calculate median by sorting array and finding middle element(s)

  • Calculate mode by finding element with highest frequency

Add your answer
right arrow

Q63. String Ka Khel Problem Statement

Ninja is creating a new game ‘String Ka Khel’ for his gaming shop. In this game, players are given ‘N’ strings. The objective is to find the maximum length of strings that can b...read more

Ans.

Compute the maximum length of a string that can be formed by joining given strings based on a condition.

  • Iterate through each string and store the count of strings ending with 'R' and 'B'.

  • Check if there are any strings ending with 'R' and 'B' that can be combined to form a longer string.

  • Return the maximum length of the string that can be formed or 0 if no combination is possible.

Add your answer
right arrow

Q64. All Prime Numbers Less Than or Equal to N

Given a positive integer N, your task is to return all the prime numbers less than or equal to N.

Note:

1) A prime number is a number that has only two factors: 1 and t...read more
Ans.

Return all prime numbers less than or equal to a given positive integer N.

  • Iterate from 2 to N and check if each number is prime using a helper function.

  • A number is prime if it is not divisible by any number from 2 to its square root.

  • Return the prime numbers in increasing order for each test case.

Add your answer
right arrow

Q65. Construct Tree from Preorder Traversal

Given a list of integers pre[] of size n, representing the preorder traversal of a special binary tree where each node has 0 or 2 children, and a boolean array isLeaf[] in...read more

Ans.

Construct a binary tree from preorder traversal and leaf node information.

  • Create a binary tree using preorder traversal and leaf node information.

  • Use a stack to keep track of nodes and their children.

  • Handle leaf nodes appropriately to construct the tree.

  • Traverse the preorder list to construct the binary tree.

Add your answer
right arrow

Q66. Minimum Number of Swaps to Achieve K-Periodic String

Given a string S of length N, an array A of length M consisting of lowercase letters, and a positive integer K, determine the minimum number of swaps require...read more

Ans.

The minimum number of swaps required to make a string K-periodic by replacing characters with elements from an array.

  • Iterate through the string and check if each character matches the character K positions ahead.

  • Count the number of characters that need to be swapped to make the string K-periodic.

  • Use the array elements to swap characters in the string.

  • Return the total number of swaps needed for each test case.

Add your answer
right arrow

Q67. Next Greater Number Problem Statement

Given a string S which represents a number, determine the smallest number strictly greater than the original number composed of the same digits. Each digit's frequency from...read more

Ans.

Given a number represented as a string, find the smallest number greater than the original with the same set of digits.

  • Iterate from right to left to find the first digit that can be swapped with a larger digit to make the number greater.

  • Swap this digit with the smallest digit to its right that is larger than it.

  • Sort the digits to the right of the swapped digit in ascending order to get the smallest number greater than the original.

  • If no such number exists, return -1.

  • Example: ...read more

Add your answer
right arrow

Q68. Zig-Zag Array Rearrangement

You are provided with an array of distinct elements, and your task is to rearrange the array elements in a zig-zag manner. Specifically, for every odd index i, the element ARR[i] sho...read more

Ans.

Rearrange array elements in a zig-zag manner where every odd index element is greater than its neighbors.

  • Iterate through the array and swap elements to satisfy the zig-zag condition.

  • Ensure that for every odd index i, ARR[i] > ARR[i-1] and ARR[i] > ARR[i+1].

  • Multiple correct answers may exist for a given array.

Add your answer
right arrow

Q69. Intersection of Linked List Problem

You are provided with two singly linked lists containing integers, where both lists converge at some node belonging to a third linked list.

Your task is to determine the data...read more

Ans.

Find the node where two linked lists merge, return -1 if no merging occurs.

  • Traverse both lists to find their lengths and the difference in lengths

  • Move the pointer of the longer list by the difference in lengths

  • Traverse both lists simultaneously until they meet at the merging point

Add your answer
right arrow

Q70. Edit Distance Problem Statement

Given two strings S and T with lengths N and M respectively, your task is to find the "Edit Distance" between these strings.

The Edit Distance is defined as the minimum number of...read more

Ans.

The task is to find the minimum number of operations required to convert one string into another using delete, replace, and insert operations.

  • Use dynamic programming to solve the problem efficiently.

  • Create a 2D array to store the edit distances between substrings of the two input strings.

  • Fill up the array based on the minimum of three possible operations: insert, delete, or replace.

  • The final answer will be the value at the bottom right corner of the array.

  • Example: For strings...read more

Add your answer
right arrow

Q71. Merge Two Sorted Linked Lists

Given two sorted linked lists, your task is to merge them into a single sorted linked list. Return the head of the newly combined list.

Note:

The given linked lists may or may not ...read more
Ans.

Merge two sorted linked lists into a single sorted linked list.

  • Create a dummy node to start the merged list

  • Compare nodes from both lists and add the smaller one to the merged list

  • Move the pointer of the merged list and the list with the smaller node

  • Handle cases where one list is exhausted before the other

  • Return the head of the merged list

Add your answer
right arrow

Q72. String Compression Problem Statement

Implement a program that performs basic string compression. When a character is consecutively repeated more than once, replace the consecutive duplicates with the count of r...read more

Ans.

Implement a program to compress a string by replacing consecutive duplicates with the count of repetitions.

  • Iterate through the string and keep track of consecutive characters and their counts.

  • Replace consecutive duplicates with the count of repetitions.

  • Ensure the count of repetitions is ≤ 9.

  • Return the compressed string.

Add your answer
right arrow

Q73. Flatten a Linked List

You are provided with a linked list of 'N' nodes. Each node contains two pointers: NEXT, pointing to the next node in the list, and CHILD, pointing to a linked list. Each child linked list...read more

Ans.

Flatten a linked list of sorted child linked lists into a single sorted linked list.

  • Traverse the linked list and maintain a priority queue to keep track of the next smallest element.

  • Merge the child linked lists into the priority queue while traversing the main linked list.

  • Pop elements from the priority queue to create the final flattened linked list.

Add your answer
right arrow

Q74. Find Maximum Element Between Two Nodes in a BST

Given a Binary Search Tree (BST) and two integers, NODE1 and NODE2, determine the maximum element found in the path between NODE1 and NODE2.

Explanation:

A Binary...read more

Ans.

Find the maximum element between two nodes in a Binary Search Tree (BST) path.

  • Traverse the BST to find the path between NODE1 and NODE2.

  • Keep track of the maximum element encountered in the path.

  • Return the maximum element found, or -1 if NODE1 or NODE2 are not in the BST or no elements exist between them.

Add your answer
right arrow

Q75. Word Search Problem Statement

Given a matrix of characters with dimensions N * M, you need to process 'Q' queries. For each query, you are given a word 'W' and you must determine if you can form word 'W' by sel...read more

Ans.

Given a matrix of characters, determine if a word can be formed by selecting adjacent characters.

  • Parse input to get matrix dimensions, characters, and queries

  • For each query, search for the word in the matrix by checking adjacent characters

  • Output '1' if word is present, '0' if not

Add your answer
right arrow

Q76. Ninja's Pattern with Powers of 2

Ninja, who loves playing with numbers, sets out to arrange numbers within 'N' rows. The unique arrangement follows these rules: the first row contains 1 number, the second row c...read more

Ans.

Generate a pattern of numbers in rows following a specific sequence based on powers of 2.

  • Start with 1 number in the first row, 2 numbers in the second row, 4 numbers in the third row, and so on based on powers of 2.

  • Fill the pattern with numbers in increasing sequence from 1 to 9, recycling back to 1 after reaching 9.

  • Output the pattern for a given number 'N' of rows.

  • Example: For N = 4, the pattern would be 1, 23, 4567, 89123456.

Add your answer
right arrow

Q77. Problem: Pair Sum in a Binary Search Tree

Given a Binary Search Tree (BST) and an integer 'S', your task is to find all pairs of nodes within the BST that total to 'S' and return these pairs. If no such pair ex...read more

Ans.

Find pairs of nodes in a BST that sum up to a given value 'S'.

  • Traverse the BST in-order to get a sorted list of nodes.

  • Use two pointers approach to find pairs with sum 'S'.

  • Keep track of visited nodes to avoid using the same node twice in a pair.

Add your answer
right arrow

Q78. Max Element in the Path in a Binary Search Tree

Given a Binary Search Tree (BST) and two integers, NODE1 and NODE2, determine the maximum element found along the path from NODE1 to NODE2.

The binary search tree...read more

Ans.

Find the maximum element in the path from NODE1 to NODE2 in a Binary Search Tree.

  • Traverse the BST from NODE1 to NODE2 while keeping track of the maximum element encountered.

  • If NODE1 or NODE2 does not exist in the BST, return -1.

  • The path does not include the values of NODE1 and NODE2 themselves, except when no intermediary nodes exist.

Add your answer
right arrow

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

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

Q81. Palindrome Partitioning Problem Statement

You are given a string S. Your task is to partition S such that every substring of the partition is a palindrome. Your objective is to return all possible palindrome pa...read more

Ans.

Given a string, partition it into palindromes and return all possible configurations.

  • Use backtracking to generate all possible palindrome partitions

  • Check if each substring is a palindrome before adding it to the partition

  • Return all valid partitions as an array of strings

Add your answer
right arrow

Q82. Longest Substring Without Repeating Characters Problem Statement

Given a string S of length L, determine the length of the longest substring that contains no repeating characters.

Example:

Input:
"abacb"
Output...read more
Ans.

Find the length of the longest substring without repeating characters in a given string.

  • Use a sliding window approach to keep track of the longest substring without repeating characters.

  • Use a hashmap to store the index of each character as it appears in the string.

  • Update the start index of the window when a repeating character is found.

  • Calculate the maximum length of the window as you iterate through the string.

  • Return the maximum length as the result.

Add your answer
right arrow

Q83. Missing Numbers Problem Statement

You are provided with an array called ARR, consisting of distinct positive integers. Your task is to identify all the numbers that fall within the range of the smallest and lar...read more

Ans.

Identify missing numbers within the range of smallest and largest elements in an array.

  • Find the smallest and largest elements in the array.

  • Generate a list of numbers within the range of smallest and largest elements.

  • Remove the numbers that are present in the array to get the missing numbers.

  • Sort and return the missing numbers.

Add your answer
right arrow

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

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

Q86. Paths in a Matrix Problem Statement

Given an 'M x N' matrix, print all the possible paths from the top-left corner to the bottom-right corner. You can only move either right (from (i,j) to (i,j+1)) or down (fro...read more

Ans.

Print all possible paths from top-left to bottom-right in a matrix by moving only right or down.

  • Use backtracking to explore all possible paths from top-left to bottom-right in the matrix.

  • At each cell, recursively explore moving right and down until reaching the bottom-right corner.

  • Keep track of the current path and add it to the result when reaching the destination.

Add your answer
right arrow

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

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

Q89. Minimum Cost to Buy Oranges Problem Statement

You are given a bag of capacity 'W' kg and a list 'cost' of costs for packets of oranges with different weights. Each element at the i-th position in the list indic...read more

Ans.

Find the minimum cost to purchase a specific weight of oranges given the cost of different weight packets.

  • Iterate through the list of costs and find the minimum cost to achieve the desired weight

  • Keep track of the total cost while considering available packet weights

  • Return -1 if it is not possible to buy exactly the desired weight

Add your answer
right arrow

Q90. In question 2 when there are ‘n’ in the String whose position shouldn’t get affected during the swapping process

Ans.

Explaining how to handle 'n' in a string during swapping process

  • Identify the positions of 'n' in the string

  • Exclude those positions from the swapping process

  • Use a temporary variable to swap the characters

  • Ensure the swapped characters are not 'n'

  • Return the modified string

View 1 answer
right arrow

Q91. Running Median Problem

Given a stream of integers, calculate and print the median after each new integer is added to the stream.

Output only the integer part of the median.

Example:

Input:
N = 5 
Stream = [2, 3,...read more
Ans.

Calculate and print the median after each new integer is added to the stream.

  • Use a min heap to store the larger half of the numbers and a max heap to store the smaller half of the numbers.

  • Keep the two heaps balanced by ensuring the size difference is at most 1.

  • If the total number of elements is odd, the median is the top element of the larger heap. If even, average the tops of both heaps.

  • Update the heaps as new elements are added to the stream.

Add your answer
right arrow

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

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

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

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

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

Q97. A String was given with a lot of words in it and I had to reverse all the words

Ans.

Reverse all the words in a given string

  • Split the string into an array of words

  • Loop through the array and reverse each word

  • Join the reversed words back into a string

View 3 more answers
right arrow

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

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

Q100. 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
1
2
3
4
5
6
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 for Freshers

based on 365 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

Infosys Logo
3.6
 • 4.5k Interview Questions
Paytm Logo
3.3
 • 458 Interview Questions
CGI Group Logo
4.0
 • 362 Interview Questions
Goldman Sachs Logo
3.5
 • 346 Interview Questions
Tata Projects Logo
4.2
 • 297 Interview Questions
Ericsson Logo
4.1
 • 274 Interview Questions
View all
Top Amazon Interview Questions And Answers
Share an Interview