Amazon
500+ SK Patodia Interview Questions and Answers
Q101. 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
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.
Q102. 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
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
Q103. 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
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
To find the maximum difference between a node and its descendant in the same path in a binary tree, we can perform a depth-first search while keeping track of the minimum value encountered so far.
Perform a depth-first search on the binary tree, keeping track of the minimum value encountered so far in the path.
At each node, calculate the difference between the current node value and the minimum value encountered so far in the path.
Update the maximum difference found so far if ...read more
I would rate my basic communication skills as strong and my confidence as high.
I have experience effectively communicating with team members and stakeholders.
I am comfortable presenting my ideas and discussing technical concepts.
I actively seek feedback to improve my communication skills.
I have successfully led meetings and discussions on project requirements.
Q106. 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
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
Kruskal's algorithm finds MST by sorting edges, adding smallest edge that doesn't create a cycle, repeat until all vertices are connected.
Sort all edges in non-decreasing order of their weights.
Initialize an empty graph to store the MST.
Iterate through sorted edges and add the smallest edge that doesn't create a cycle in the MST.
Repeat until all vertices are connected in the MST.
Q108. Subsequences of String Problem Statement
You are provided with a string 'STR'
that consists of lowercase English letters ranging from 'a' to 'z'. Your task is to determine all non-empty possible subsequences of...read more
Generate all possible subsequences of a given string.
Use recursion to generate all possible subsequences by including or excluding each character in the string.
Maintain the order of characters while generating subsequences.
Handle base cases where the string is empty or has only one character.
Store the generated subsequences in an array of strings.
Q109. Clone Linked List with Random Pointer Problem Statement
Given a linked list where each node has two pointers: one pointing to the next node and another which can point randomly to any node in the list or null, ...read more
Cloning a linked list with random pointers by creating new nodes rather than copying references.
Create a deep copy of the linked list by iterating through the original list and creating new nodes with the same values.
Update the random pointers of the new nodes by mapping the original node's random pointer index to the corresponding new node.
Ensure the cloned linked list is an exact copy of the original by validating the values and random pointers.
The cloning process can be ac...read more
Q110. Subtree of Another Tree Problem Statement
Given two binary trees, T and S, determine whether S is a subtree of T. The tree S should have the same structure and node values as a subtree of T.
Explanation:
A subt...read more
Given two binary trees T and S, determine if S is a subtree of T with the same structure and node values.
Traverse both trees and check if S is a subtree of T at each node
Use recursion to compare subtrees
Handle edge cases like empty trees or null nodes
Q111. Triplet Count in a Sorted Doubly Linked List Problem
Count the number of triplets in a sorted doubly linked list such that their sum equals a given integer 'X'. The list is composed of distinct node values.
Exp...read more
Count the number of triplets in a sorted doubly linked list such that their sum equals a given integer 'X'.
Iterate through the linked 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 while traversing the list.
Return the final count of triplets that sum up to 'X'.
Q112. Chocolate Distribution Problem
You are given an array/list CHOCOLATES
of size 'N', where each element represents the number of chocolates in a packet. Your task is to distribute these chocolates among 'M' stude...read more
Distribute chocolates among students to minimize difference between largest and smallest packets.
Sort the array of chocolates packets.
Use sliding window technique to find the minimum difference between packets distributed to students.
Return the minimum difference as the output.
Q113. Matrix Median Problem Statement
You are provided with a matrix containing 'N' rows and 'M' columns filled with integers. Each row is sorted in non-decreasing order. Your task is to find the overall median of th...read more
Find the overall median of a matrix with sorted rows.
Merge all elements of the matrix into a single sorted array
Calculate the median of the merged array
Handle odd number of elements by directly finding the middle element
Q114. Count Triplets in a Sorted Doubly Linked List
You are provided with an integer X
and a non-decreasing sorted doubly linked list consisting of distinct nodes.
Your task is to find and return the count of triplet...read more
Count triplets in a sorted doubly linked list that sum up to a given value.
Iterate through the list and for each node, find pairs that sum up to X-nodeValue.
Use two pointers approach to find pairs efficiently.
Keep track of count of triplets found while iterating through the list.
Q115. Number of Islands Problem Statement
You are provided with a 2-dimensional matrix having N
rows and M
columns, containing only 1s (land) and 0s (water). Your goal is to determine the number of islands in this ma...read more
The task is to find the number of islands present in a 2-dimensional array filled with ones and zeroes.
Iterate through each cell in the array
If the cell is land (1) and not visited, perform a depth-first search to find all connected land cells
Increment the count of islands for each connected component found
Q116. What do you know about risk management?
Risk management involves identifying, assessing, and prioritizing risks to minimize their impact on an organization.
Risk management is a process of identifying potential risks and taking steps to mitigate them.
It involves assessing the likelihood and impact of risks, and prioritizing them based on their severity.
Risk management strategies may include risk avoidance, risk reduction, risk transfer, or risk acceptance.
Examples of risks that may be managed include financial risks...read more
Q117. Sort Linked List Based on Actual Values
Given a Singly Linked List of integers that are sorted based on their absolute values, the task is to sort the linked list based on the actual values.
The absolute value ...read more
Sort a Singly Linked List based on actual values instead of absolute values.
Traverse the linked list and store the nodes in an array.
Sort the array based on the actual values of the nodes.
Reconstruct the linked list using the sorted array.
Q118. Who many types in shopping ?
There are several types of shopping including online, in-store, grocery, luxury, thrift, and impulsive.
Online shopping - buying products through the internet
In-store shopping - physically going to a store to purchase products
Grocery shopping - buying food and household items at a grocery store
Luxury shopping - purchasing high-end, expensive items
Thrift shopping - buying second-hand items at a lower cost
Impulsive shopping - making unplanned purchases on a whim
Q119. Ninja's Jump Task
The Ninja has been given a challenge by his master to reach the last stone. These stones are represented as an array of numbers. The Ninja can jump using either odd-numbered or even-numbered j...read more
Find the number of starting indices from which a Ninja can reach the last stone by following specific jump rules.
Iterate through the array and keep track of the indices that satisfy the jump rules.
Use dynamic programming to efficiently determine the number of starting indices.
Consider odd and even jumps separately to handle the different conditions.
Example: For the input [10, 13, 12, 14, 15], the Ninja can start at indices 0 and 1 to reach the last stone.
Q120. Flip Bit to Win Problem Statement
You are given a task to help ninjas maximize their practice area in a dense forest represented by a sequence of trees (1s) and empty places (0s) in the binary representation of...read more
Given an integer representing a binary sequence, find the maximum consecutive ones by flipping one bit.
Iterate through the binary representation of the integer to find the longest sequence of ones.
Track the positions of zeros to determine where to flip a bit for maximizing consecutive ones.
Update the count of consecutive ones after flipping a zero to one.
Return the maximum length of consecutive ones obtained by flipping one bit.
Q121. Saving Money Problem Statement
Ninja is adventurous and loves traveling while being mindful of his expenses. Given a set of 'N' stations connected by 'M' trains, each train starting from station 'A' and reachin...read more
Given a set of stations connected by trains, find the cheapest fare from a source to a destination with a maximum number of stops allowed.
Iterate through all possible routes with up to 'K' stops using a graph traversal algorithm like DFS or BFS.
Keep track of the cost for each route and return the minimum cost found.
If no route is found within the maximum stops allowed, return '-1'.
Q122. Find the Row with the Maximum Number of 1's
You are given a non-empty grid MAT
with 'N' rows and 'M' columns, where each element is either 0 or 1. All rows are sorted in ascending order.
Your task is to determi...read more
Find the row with the maximum number of 1's in a grid of 0's and 1's.
Iterate through each row of the grid and count the number of 1's in each row.
Keep track of the row index with the maximum number of 1's seen so far.
Return the index of the row with the maximum number of 1's.
Q123. Knight Probability in Chessboard
Calculate the probability that a knight remains on an N x N chessboard after making K moves. Initially, the knight is placed at a given position on the board. It can move in any...read more
Calculate the probability that a knight remains on an N x N chessboard after making K moves.
Use dynamic programming to calculate the probability of the knight staying on the board after each move.
Consider all possible moves the knight can make from its current position.
Keep track of the probabilities at each position on the board after each move.
Normalize the probabilities at the end to get the final result accurate to six decimal places.
Q124. Maximum of All Subarrays of Size K
You are provided with an array A
containing N
integers. Your task is to determine the maximum element in every contiguous subarray of size K
as you move from left to right thr...read more
Find maximum element in every contiguous subarray of size K in an array.
Iterate through the array and maintain a deque to store the indices of elements in decreasing order.
Remove indices from the deque that are outside the current window of size K.
The front of the deque will always have the index of the maximum element in the current window.
Q125. The Celebrity Problem
Imagine there are 'N' people at a party, each assigned a unique ID from 0 to N-1. A celebrity at the party is a person who is known by everyone but knows no one else.
Problem Statement:
Yo...read more
Identify the celebrity at a party where one person knows everyone but is not known by anyone.
Use a two-pointer approach to eliminate non-celebrity candidates.
Start with two pointers at the beginning and end of the party.
If A knows B, A cannot be the celebrity; move A to B.
If A does not know B, B cannot be the celebrity; move B to A.
Repeat until only one person remains; check if this person is known by everyone.
Return the ID of the celebrity or -1 if none exists.
Q126. Reachable Nodes Problem Statement
You are provided with a graph containing 'N' nodes and 'M' unidirectional edges. Your task is to determine the number of nodes that can be reached from each node 'i', where 0 <...read more
The task is to determine the number of nodes that can be reached from each node in a graph.
Create an adjacency list to represent the graph.
Use Depth First Search (DFS) to traverse the graph and count reachable nodes from each node.
Initialize a count array to store the number of reachable nodes for each node.
Update the count array while traversing the graph using DFS.
Output the count array for each test case.
Q127. 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
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.
Check if two strings are anagrams by comparing the sorted versions of the strings.
Sort both strings and compare if they are equal.
Use a hashmap to store the frequency of characters in each string and compare the maps.
Ignore spaces and punctuation when comparing the strings.
Designing a system to create a clone of Facebook
Identify key features of Facebook such as user profiles, news feed, friend connections, messaging, etc.
Design database schema to store user data, posts, comments, likes, etc.
Implement user authentication and authorization mechanisms for security.
Develop front-end and back-end components using technologies like React, Node.js, and MongoDB.
Scale the system to handle millions of users by using load balancing, caching, and sharding....read more
Q130. Favourite Operation - Problem Statement
Ninja has studied the bitwise operations ‘AND’ and ‘XOR’. He received an assignment that involves these operations and needs help to complete it efficiently before the de...read more
Calculate bitwise 'AND' and 'XOR' of subarrays of size at most K in an array efficiently.
Iterate through all subarrays of size at most K and calculate bitwise 'AND'.
Calculate the 'XOR' of all the bitwise 'AND' results to get the final output.
Optimize the solution to handle large input sizes efficiently.
Q131. Critical Connection Problem Statement
In a network with 'N' system nodes, identified from 0 to N-1, and 'M' connections, determine all critical connections. A connection is critical if its removal disrupts the ...read more
Implement a function to find critical connections in a network with system nodes and connections.
Create an adjacency list to represent the network connections.
Use Tarjan's algorithm to find critical connections in the network.
Output the count of critical connections and the pairs of nodes involved.
Handle multiple test cases efficiently.
Ensure that the removal of a critical connection disrupts network connectivity.
Q132. 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
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.
Q133. 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
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.
Q134. Return in Row Wave Form Problem Statement
You are provided with a 2D array having dimensions 'N*M'. Your task is to traverse the elements row-wise and return a single-dimensional array which stores these elemen...read more
Traverse a 2D array row-wise and return elements in a wave pattern.
Traverse the 2D array row-wise and store elements alternately in a wave pattern.
For each row, store elements from left to right for odd rows and from right to left for even rows.
Return the final 1D array representing the wave pattern of elements.
Q135. Snake and Ladder Problem Statement
Given a 'Snake and Ladder' board with N rows and N columns, where positions are numbered from 1 to (N*N) starting from the bottom left, alternating direction each row, find th...read more
Find the minimum number of dice throws required to reach the last cell on a 'Snake and Ladder' board.
Use Breadth First Search (BFS) algorithm to find the shortest path on the board.
Keep track of visited cells and the number of dice throws required to reach each cell.
Consider the presence of snakes and ladders while calculating the next possible moves.
Return -1 if the last cell is unreachable.
Q136. Squares of a Sorted Array Problem Statement
You are given an array/list ARR
consisting of N
integers. Your task is to generate a new array/list containing the squares of each element in ARR
, with the resulting ...read more
Given an array of integers, generate a new array with the squares of each element sorted in increasing order.
Iterate through the array and square each element
Sort the squared elements in increasing order
Return the sorted array
Q137. Valid String Problem Statement
Given a string S
consisting solely of the characters '('
, ')'
, and '*'
, determine if it is a valid string.
Definition of Valid String:
1. Every left parenthesis '(' must have a co...read more
Determine if a given string consisting of '(' , ')' and '*' is valid based on certain rules.
Iterate through the string and keep track of the count of left parentheses, right parentheses, and stars.
Use a stack to keep track of the positions of left parentheses.
If at any point the count of right parentheses exceeds the count of left parentheses + stars, the string is invalid.
If the stack is not empty at the end, the string is invalid.
Otherwise, the string is valid.
Q138. Convert a Binary Tree to its Sum Tree
Given a binary tree of integers, convert it to a sum tree where each node is replaced by the sum of the values of its left and right subtrees. Set leaf nodes to zero.
Input...read more
Convert a binary tree to a sum tree by replacing each node with the sum of its left and right subtrees.
Traverse the tree in postorder fashion.
For each node, calculate the sum of its left and right subtrees and update the node's value.
Set leaf nodes to zero.
Return the level order traversal of the modified tree.
Q139. Circular Array Loop Problem Statement
Given a circular array ARR
of size N
consisting of positive and negative integers, determine if there is a cycle present in the array. You can make movements based on the v...read more
Determine if a circular array has a cycle present, following specific movement rules.
Iterate through the array and check for cycles following the given movement rules.
Keep track of visited indices to detect cycles.
Handle both clockwise and counterclockwise movements separately.
Return 'True' if a cycle is found, 'False' otherwise.
Q140. Longest Substring with At Most K Distinct Characters
Given a string S
of length N
and an integer K
, find the length of the longest substring that contains at most K
distinct characters.
Input:
The first line co...read more
Find the length of the longest substring with at most K distinct characters in a given string.
Use a sliding window approach to keep track of the characters and their counts within the window.
Maintain a hashmap to store the characters and their frequencies.
Update the window size and characters count as you iterate through the string.
Return the maximum window size encountered for each test case.
Q141. Word Break Problem Statement
You are given a list of N
strings called A
. Your task is to determine whether you can form a given target string by combining one or more strings from A
.
The strings from A
can be u...read more
Given a list of strings, determine if a target string can be formed by combining one or more strings from the list.
Iterate through all possible combinations of strings from the list to form the target string.
Use recursion to try different combinations of strings.
Check if the current combination forms the target string.
Return true if a valid combination is found, otherwise return false.
Q142. 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
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.
Q143. Given n coins for two players playing a game. Each player picks coins from the given n coins in such a way that he can pick 1 to 5 coins in one turn and the game continues for both the players. The player who p...
read moreThe player who picks the last coin loses the game.
The game starts with n coins.
Each player can pick 1 to 5 coins in one turn.
The player who picks the last coin loses the game.
Determine if the given n coins will result in a win or loss for the starting player.
Q144. Given an Infix expression, how to evaluate its answer
Infix expression can be evaluated using the concept of operator precedence and associativity.
Convert the infix expression to postfix expression using stack data structure
Evaluate the postfix expression using stack data structure
Use operator precedence and associativity rules to determine the order of evaluation
Parentheses can be used to override the default order of evaluation
Q145. Check If Linked List Is Palindrome
Given a singly linked list of integers, determine if the linked list is a palindrome.
Explanation:
A linked list is considered a palindrome if it reads the same forwards and b...read more
Check if a given singly linked list of integers is a palindrome or not.
Traverse the linked list to find the middle element using slow and fast pointers.
Reverse the second half of the linked list.
Compare the first half with the reversed second half to determine if it's a palindrome.
Q146. Total Unique Paths Problem Statement
You are located at point ‘A’, the top-left corner of an M x N matrix, and your target is point ‘B’, the bottom-right corner of the same matrix. Your task is to calculate the...read more
Calculate total unique paths from top-left to bottom-right corner of a matrix by moving only right or down.
Use dynamic programming to solve the problem efficiently.
Create a 2D array to store the number of unique paths for each cell.
Initialize the first row and first column with 1 as there is only one way to reach them.
For each cell (i, j), the number of unique paths is the sum of paths from the cell above and the cell to the left.
Return the value in the bottom-right corner of...read more
Q147. Find First Repeated Character in a String
Given a string 'STR' composed of lowercase English letters, identify the character that repeats first in terms of its initial occurrence.
Example:
Input:
STR = "abccba"...read more
Find the first repeated character in a given string of lowercase English letters.
Iterate through the string and keep track of characters seen so far.
Return the first character that repeats, not just the first repeating character.
If no repeating character is found, return '%'.
Mutex is used for exclusive access to a resource by only one thread at a time, while Semaphores can allow multiple threads to access a resource simultaneously.
Mutex is binary and allows only one thread to access a resource at a time, while Semaphores can have a count greater than one.
Mutex is used for protecting critical sections of code, while Semaphores can be used for controlling access to a pool of resources.
Example: Mutex can be used to control access to a shared variabl...read more
Q149. Count Ways to Reach the N-th Stair Problem Statement
You are provided with a number of stairs, and initially, you are located at the 0th stair. You need to reach the Nth stair, and you can climb one or two step...read more
The problem involves finding the number of distinct ways to climb N stairs by taking 1 or 2 steps at a time.
Use dynamic programming to solve the problem efficiently.
The number of ways to reach the Nth stair is the sum of the number of ways to reach the (N-1)th stair and the (N-2)th stair.
Handle base cases for N=0 and N=1 separately.
Apply modulo operation to avoid overflow while calculating the result.
Consider using memoization to optimize the solution by storing intermediate ...read more
Q150. Maximum Sum of Non-Adjacent Nodes in a Binary Tree
Given a binary tree with integer values assigned to each node, select nodes such that their sum is maximum, ensuring no two adjacent nodes are picked.
Input:
T...read more
Find the maximum sum of non-adjacent nodes in a binary tree.
Use dynamic programming to keep track of the maximum sum at each node considering whether to include or exclude the current node.
Recursively traverse the binary tree while keeping track of the maximum sum of non-adjacent nodes.
Consider the scenarios where the current node is included in the sum or excluded from the sum to calculate the maximum possible sum.
Q151. Minimum Cost to Cross a Grid
You are given a 2D grid consisting of 'N' rows and 'M' columns. Each cell in the grid has a certain cost associated with passing through it. Your goal is to find the minimum cost to...read more
Find the minimum cost to travel from top-left to bottom-right corner of a grid.
Use dynamic programming to keep track of minimum cost to reach each cell.
Start from top-left corner and iterate through the grid to calculate minimum cost.
Consider all possible movements (UP, DOWN, LEFT, RIGHT) while staying within grid boundaries.
Update the cost for each cell by considering the minimum cost of reaching adjacent cells.
The final answer will be the cost to reach the bottom-right corn...read more
Q152. Shopping Options Problem Statement
Given arrays representing the costs of pants, shirts, shoes, and skirts, and a budget amount 'X', determine the total number of valid combinations that can be purchased such t...read more
Determine total number of valid shopping combinations within budget
Iterate through all possible combinations of items from each array
Check if the total cost of the combination is within the budget
Return the count of valid combinations
Q153. How to implement word suggestions like that in Eclipse
Word suggestions in Eclipse can be implemented using algorithms like Trie or N-gram models.
Use Trie data structure to store the dictionary of words
Implement auto-complete feature using Trie
Use N-gram models to suggest words based on context
Train the N-gram model on a large corpus of text data
Combine both approaches for better accuracy
Consider user's typing speed and frequency of words for better suggestions
Q154. Bottom View of Binary Tree
Given a binary tree, determine and return its bottom view when viewed from left to right. Assume that each child of a node is positioned at a 45-degree angle from its parent.
Nodes in...read more
Given a binary tree, return the bottom view of the tree when viewed from left to right.
Calculate the horizontal distance of each node relative to the root.
For each horizontal distance, keep track of the bottom-most node.
If two nodes share the same horizontal distance, choose the deeper node.
Return the sequence of bottom view nodes from left to right.
Q155. Bridges in a Graph Problem Statement
In an undirected graph consisting of V
vertices and E
edges, your task is to identify all the bridges within the graph. A bridge is an edge which, when removed, results in t...read more
Identify bridges in an undirected graph by finding edges that, when removed, increase the number of connected components.
Use depth-first search (DFS) to find bridges in the graph.
Keep track of discovery time and low time for each vertex during DFS.
An edge (u, v) is a bridge if low[v] > disc[u].
Sort and print the bridge pairs in ascending order of vertices.
Example: If the input graph has vertices 0, 1, 2, 3, 4 and edges (0, 1), (1, 2), (2, 3), (3, 4), (0, 4), then the bridge i...read more
Q156. Square Root with Decimal Precision Problem Statement
You are provided with two integers, 'N' and 'D'. Your objective is to determine the square root of the number 'N' with a precision up to 'D' decimal places. ...read more
Implement a function to find the square root of a number with a given precision up to a specified number of decimal places.
Implement a function that takes two integers N and D as input and returns the square root of N with precision up to D decimal places.
Use mathematical algorithms like Newton's method or binary search to approximate the square root with the desired precision.
Ensure that the difference between the computed result and the true square root is less than 10^(-D)...read more
Q157. Amazing Strings Problem Statement
Determine if the third string contains all the characters from both the first and second strings in any order. If so, return "YES"; otherwise, return "NO".
Input:
Line 1: First...read more
Check if the third string contains all characters from the first and second strings in any order.
Create a frequency map for characters in the first and second strings.
Check if the frequency of characters in the third string matches the frequency map of the first and second strings.
Return 'YES' if all characters are present in the third string, otherwise return 'NO'.
Q158. Wich programming languages do you use in your work
I primarily use Java and Python in my work as a Customer Service Associate.
I use Java for developing and maintaining our internal tools and systems.
I use Python for data analysis and automation tasks.
I also have experience with SQL for querying databases.
Additionally, I have some knowledge of HTML, CSS, and JavaScript for troubleshooting website issues.
Q159. Explain the difference between ArrayList and LinkedList in Java. ArrayList is implemented as a dynamic array, while LinkedList is a doubly linked list. ArrayList provides fast random access (O(1) complexity) bu...
read moreArrayList is preferred for frequent retrieval operations due to fast random access, while LinkedList is suitable for frequent insertions/deletions with fast O(1) complexity.
Use ArrayList for scenarios where frequent retrieval operations are needed, such as searching for elements in a large collection.
Choose LinkedList when frequent insertions/deletions are required, like maintaining a queue or stack with dynamic size.
Consider memory overhead and performance trade-offs when de...read more
Q160. Sort Array by Set Bit Count
You have an array of N positive integers. Your goal is to sort this array in descending order based on the number of set bits in the binary representation of each integer.
In other w...read more
Sort array of positive integers based on set bit count in descending order.
Count set bits for each integer using bitwise operations.
Implement a custom comparator function to sort the array based on set bit count.
Handle cases where integers have the same set bit count by retaining their original order.
Q161. Product Of Array Except Self Problem Statement
You are provided with an integer array ARR
of size N
. You need to return an array PRODUCT
such that PRODUCT[i]
equals the product of all the elements of ARR
except...read more
Return an array of products of all elements in an array except the current element.
Iterate through the array twice to calculate the product of all elements to the left and right of each element.
Use two arrays to store the products of elements to the left and right of each element.
Multiply the corresponding elements from the left and right product arrays to get the final product array.
Q162. Maximum Product Subarray Problem Statement
Given an array of integers, determine the contiguous subarray that produces the maximum product of its elements.
Explanation:
A subarray can be derived from the origin...read more
Find the contiguous subarray with the maximum product of elements in an array.
Iterate through the array and keep track of the maximum and minimum product ending at each index.
Update the maximum product by taking the maximum of current element, current element * previous maximum, and current element * previous minimum.
Update the minimum product by taking the minimum of current element, current element * previous maximum, and current element * previous minimum.
Return the maximu...read more
Q163. First Negative Integer in Every Window of Size K
Given an array of integers 'ARR' and an integer 'K', determine the first negative integer in every contiguous subarray (or window) of size 'K'. If a window does ...read more
Find the first negative integer in every window of size K in an array.
Iterate through the array using a sliding window approach of size K
For each window, find the first negative integer and output it, if none exists output 0
Handle edge cases where window size is greater than array size
Q164. Find Pair with Maximum GCD in an Array
Given an array of positive integers, your task is to find the GCD (Greatest Common Divisor) of a pair of elements such that it is the maximum among all possible pairs. The...read more
Find the pair with the maximum GCD in an array of positive integers.
Iterate through all pairs of elements in the array.
Calculate the GCD of each pair using Euclidean algorithm.
Keep track of the maximum GCD found so far.
Return the maximum GCD value.
Q165. Count Set Bits Problem Statement
Given a positive integer N
, compute the total number of '1's in the binary representation of all numbers from 1 to N. Return this count modulo 1e9+7 because the result can be ve...read more
Count the total number of set bits in the binary representation of numbers from 1 to N modulo 1e9+7.
Use bitwise operations to count the set bits in each number from 1 to N.
Consider using dynamic programming to optimize the solution.
Remember to return the count modulo 1e9+7 to handle large results.
Q166. Transform BST to Greater Sum Tree
Given a Binary Search Tree (BST) of integers, the task is to convert it into a greater sum tree. In this transformation, each node's value is replaced by the sum of values of a...read more
Convert a Binary Search Tree into a Greater Sum Tree by replacing each node's value with the sum of values of all nodes greater than the current node.
Traverse the BST in reverse inorder (right, root, left) to visit nodes in descending order.
Keep track of the sum of visited nodes and update each node's value with this sum.
Recursively apply the above steps to all nodes in the BST.
Example: For the given BST, the transformed tree will have values 139, 137, 130, 119, 104, 75, 40, ...read more
Q167. Sorted Linked List to Balanced BST Problem Statement
Given a singly linked list where nodes contain values in increasing order, your task is to convert it into a Balanced Binary Search Tree (BST) using the same...read more
Convert a sorted linked list into a Balanced Binary Search Tree (BST) using the same data values.
Create a function to convert the linked list to an array for easier manipulation.
Implement a function to build a Balanced BST from the array recursively.
Ensure the height difference of the subtrees is no more than 1 for each node.
Use level order traversal to output the values of the BST nodes.
Handle NULL nodes by representing them with -1 in the output.
Q168. Fishmonger Toll Optimization Problem
A fishmonger needs to transport goods from a port to a market, crossing multiple states each requiring a toll. The goal is to minimize the toll costs while ensuring the jour...read more
The Fishmonger Toll Optimization Problem involves minimizing toll costs while ensuring timely delivery of goods from a port to a market.
Given 'N' states and a time limit 'M', find the smallest toll amount to reach the market from the port within the given time.
Use dynamic programming to solve the problem efficiently.
Consider both time and toll matrices to calculate the minimum toll cost.
Return -1 if it is not possible to reach the market within the given time limit.
Q169. Character Formation Check
Determine if the second string STR2
can be constructed using characters from the first string STR1
. Both strings may include any characters.
Input:
The first line contains an integer T...read more
Check if second string can be formed using characters from the first string.
Iterate through each character in STR2 and check if it exists in STR1.
Use a hashmap to store the frequency of characters in STR1 for efficient lookup.
Return 'YES' if all characters in STR2 are found in STR1, otherwise return 'NO'.
Q170. Connect Ropes with Minimum Cost
Given 'N' ropes, each having different lengths, your task is to connect these ropes into one single rope. The cost to connect two particular ropes is equal to the sum of their le...read more
Connect ropes with different lengths into one single rope with minimum cost by merging the smallest ropes first.
Sort the lengths of ropes 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 the merging process until all ropes are connected.
Return the total cost as the minimum cost to connect all ropes.
Q171. Langford Pairing Problem Statement
Given a positive integer N
, you are required to generate a list of integers of size 2N
such that it contains all the integers from 1 to N
, both included, twice. These integers...read more
Generate Langford pairing for given N, return 'Valid' if correct, 'Invalid' if not.
Generate a list of integers of size 2N with all integers from 1 to N twice.
Arrange integers according to Langford pairing rules.
Return 'Valid' if pairing is correct, 'Invalid' if not.
If no valid pairing possible, return list with only -1 element.
Q172. Next Smaller Element Problem Statement
You are provided with an array of integers ARR
of length N
. Your task is to determine the next smaller element for each array element.
Explanation:
The Next Smaller Elemen...read more
Given an array of integers, find the next smaller element for each element in the 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 smaller element is found or the stack is empty.
If no smaller element is found, output -1 for that element.
Q173. Problem Statement: Sorted Subsequence of Size 3
Given an array composed of N elements, your task is to identify a subsequence with exactly three elements where these elements maintain a strictly increasing orde...read more
Identify a subsequence of size 3 with strictly increasing order in an array.
Iterate through the array and keep track of the smallest and second smallest elements encountered so far.
If a third element greater than both is found, return the subsequence.
Handle edge cases where no valid subsequence exists.
Q174. Merge Two Sorted Linked Lists Problem Statement
You are provided with two sorted linked lists. Your task is to merge them into a single sorted linked list and return the head of the combined linked list.
Input:...read more
Merge two sorted linked lists into a single sorted linked list without using additional space.
Create a dummy node to start the merged list
Compare the nodes of both lists and link them accordingly
Move the pointer to the next node in the merged list
Handle cases where one list is empty or both lists are empty
Time complexity: O(n), Space complexity: O(1)
Q175. Add Two Numbers as Linked Lists
You are given two singly linked lists, where each list represents a positive number without any leading zeros.
Your task is to add these two numbers and return the sum as a linke...read more
Add two numbers represented as linked lists and return the sum as a linked list.
Traverse both linked lists simultaneously while adding corresponding nodes and carry over the sum if needed
Handle cases where one linked list is longer than the other by adding remaining nodes with carry
Create a new linked list to store the sum and return its head node
Q176. Course Schedule Problem Statement
You are enrolled as a student and must complete N
courses, numbered from 1 to N, to earn your degree.
Some courses have prerequisites, which means that to take course i
, you mu...read more
Determine if it is feasible to complete all courses with given prerequisites.
Create a graph representation of the courses and prerequisites.
Check for cycles in the graph using topological sorting.
If there are no cycles, all courses can be completed.
Example: For N=2 and prerequisites=[[1, 2]], output is 'Yes'.
Q177. There is a big file containing numbers and we have to sort all of them
We can use any sorting algorithm like quicksort, mergesort, heapsort, etc.
Choose the appropriate sorting algorithm based on the size of the file and the range of numbers
Implement the chosen algorithm in the programming language of choice
Read the numbers from the file into an array or list
Apply the sorting algorithm to the array or list
Write the sorted numbers back to the file
Q178. Height of Binary Tree
You are provided with the Inorder and Level Order traversals of a Binary Tree composed of integers. Your goal is to determine the height of this Binary Tree without actually constructing i...read more
Calculate the height of a Binary Tree using Inorder and Level Order traversals without constructing the tree.
Use the properties of Inorder and Level Order traversals to determine the height of the Binary Tree.
The height of a Binary Tree is the number of edges on the longest path from the root to a leaf node.
Consider edge cases like a single node tree or empty tree while calculating the height.
Q179. Flatten BST to a Sorted List
The objective is to transform a given Binary Search Tree (BST) into a right-skewed BST, effectively flattening it into a sorted list. In the resulting structure, every node's left c...read more
Transform a Binary Search Tree into a right-skewed BST, flattening it into a sorted list.
Implement a function to flatten the BST into a sorted list by linking nodes through right children.
Traverse the BST in-order and adjust the pointers to create the right-skewed structure.
Ensure that every node's left child is NULL in the resulting flattened BST.
Output the values of nodes in the skewed BST in level order for each test case.
Handle cases where nodes are NULL (-1) appropriatel...read more
Q180. there is an infinite stair case and there are n rounds. in i'th round we can jump i steps at one or discard them. it is given that k'th step is broken , find the max height we can reach with out stepping on the...
read moreGiven an infinite staircase with a broken kth step, find the maximum height we can reach in n rounds of jumping i steps.
We can start by jumping the maximum number of steps in each round until we reach the broken step.
After reaching the broken step, we can discard the i steps that would land us on the broken step and jump the remaining steps.
We can continue this pattern until we reach the maximum height we can reach without stepping on the broken step.
Q181. What are the advantages and disadvantages of using Java’s synchronized keyword for thread synchronization? The synchronized keyword ensures that only one thread can access a block of code at a time. It prevents...
read moreReentrantLock should be used instead of synchronized when more flexibility and control over locking mechanisms is required.
Use ReentrantLock when you need to implement advanced locking mechanisms like tryLock() or lockInterruptibly()
ReentrantLock supports fair locking, ensuring that threads acquire the lock in the order they requested it
Explicit unlocking in ReentrantLock can help prevent deadlocks and improve performance in certain scenarios
Q182. What is the difference between == and .equals() in Java? == checks for reference equality, meaning it compares memory addresses. equals() checks for value equality, which can be overridden in user-defined class...
read moreIn Java, == checks for reference equality while equals() checks for value equality. Misuse of == can lead to logical errors.
Override equals() when you want to compare the actual content of objects in user-defined classes.
Override hashCode() method alongside equals() to ensure consistent behavior in collections like HashMap.
Implement Comparable interface and override compareTo() method for natural ordering of objects.
Q183. How does the Java garbage collector work? Garbage collection in Java automatically reclaims memory occupied by unused objects. The JVM has different types of GC algorithms, including Serial, Parallel, CMS, and...
read moreGarbage collection in Java automatically reclaims memory occupied by unused objects using different GC algorithms and memory regions.
Force garbage collection in Java can be done using System.gc() or Runtime.gc() methods.
It is generally not recommended to force garbage collection as it can disrupt the JVM's natural memory management process and cause performance issues.
Forcing garbage collection may not guarantee immediate memory reclamation and can lead to inefficient memory ...read more
Q184. What are the main features of Java 8? Java 8 introduced lambda expressions, enabling functional-style programming. The Stream API allows efficient data processing with map, filter, and reduce operations. Defaul...
read moreLambda expressions in Java 8 improve readability and maintainability by enabling concise and functional-style programming.
Lambda expressions allow writing more compact code by reducing boilerplate code.
They enable passing behavior as arguments to methods, making code more modular and flexible.
Example: (a, b) -> a + b is a lambda expression that adds two numbers.
Q185. Unique Element In Sorted Array
Nobita wants to impress Shizuka by correctly guessing her lucky number. Shizuka provides a sorted list where every number appears twice, except for her lucky number, which appears...read more
Find the unique element in a sorted array where all other elements appear twice.
Iterate through the array and XOR all elements to find the unique element.
Use a hash set to keep track of elements and find the unique one.
Sort the array and check adjacent elements to find the unique one.
Q186. Find Duplicate in Array Problem Statement
You are provided with an array of integers 'ARR' consisting of 'N' elements. Each integer is within the range [1, N-1], and the array contains exactly one duplicated el...read more
Identify the duplicate element in an array of integers.
Iterate through the array and keep track of the frequency of each element using a hashmap.
Return the element with a frequency greater than 1 as the duplicate.
Time complexity can be optimized to O(N) using Floyd's Tortoise and Hare algorithm.
Example: For input [3, 1, 3, 4, 2], the output should be 3.
Q187. Kevin and his Fruits Problem Statement
Kevin has 'N' buckets, each consisting of a certain number of fruits. Kevin wants to eat at least 'M' fruits. He is looking to set a marker as high as possible such that i...read more
Find the marker value needed for Kevin to eat at least 'M' fruits from 'N' buckets.
Iterate through each bucket and calculate the difference between the number of fruits and the marker value needed to reach 'M'.
Update the marker value to be the maximum of the current marker value and the difference calculated in the previous step.
Return the final marker value as the output.
Q188. Rat in a Maze Problem Statement
You need to determine all possible paths for a rat starting at position (0, 0) in a square maze to reach its destination at (N-1, N-1). The maze is represented as an N*N matrix w...read more
Find all possible paths for a rat in a maze from source to destination.
Use backtracking to explore all possible paths in the maze.
Keep track of visited cells to avoid revisiting them.
Explore all possible directions ('U', 'D', 'L', 'R') from each cell.
Terminate the search when the destination cell is reached.
Return the list of valid paths sorted in alphabetical order.
Q189. Check if Two Trees are Mirror
Given two arbitrary binary trees, your task is to determine whether these two trees are mirrors of each other.
Explanation:
Two trees are considered mirror of each other if:
- The r...read more
Check if two binary trees are mirrors of each other based on specific criteria.
Compare the roots of both trees.
Check if the left subtree of the first tree is the mirror of the right subtree of the second tree.
Verify if the right subtree of the first tree is the mirror of the left subtree of the second tree.
Q190. Sub Matrices With Sum Zero Problem Statement
You are provided with a square matrix 'MAT' of order N. Your task is to determine the number of non-empty sub-matrices where the sum of all elements within the sub-m...read more
Count the number of sub-matrices with sum zero in a square matrix.
Iterate over all possible sub-matrices and calculate the sum of elements within each sub-matrix.
Use a hashmap to store the prefix sum of rows or columns to efficiently calculate the sum of sub-matrices.
Check for sub-matrices with sum zero and increment the count accordingly.
Return the total count of sub-matrices with sum zero.
Q191. Maximum Path Sum in a Matrix
Given an N*M matrix filled with integer numbers, determine the maximum sum that can be obtained from a path starting from any cell in the first row to any cell in the last row.
You ...read more
Find the maximum sum path in a matrix from top row to bottom row by moving down or diagonally.
Use dynamic programming to keep track of maximum sum at each cell.
At each cell, the maximum sum is the current cell value plus the maximum of the three possible previous cells.
Iterate through the matrix row by row and update the maximum sum at each cell.
Return the maximum sum found in the last row as the result.
Q192. Subset Check Problem Statement
Determine if one array is a subset of another given two integer arrays ARR1
and ARR2
of lengths 'N' and 'M' respectively.
Return True if ARR2
is a subset of ARR1
, otherwise return...read more
Check if one array is a subset of another array.
Iterate through elements of ARR2 and check if each element is present in ARR1.
Use a set data structure to efficiently check for element presence.
Return true if all elements of ARR2 are found in ARR1, otherwise return false.
Q193. Counting Distinct Elements in Every K-Sized Window
Given an array ARR
of size N
and an integer K
, determine the number of distinct elements in every K-sized window of the array. A 'K' sized window is defined as...read more
Implement a function to count distinct elements in every K-sized window of an array.
Use a sliding window approach to keep track of distinct elements in each window
Use a hashmap to store the frequency of elements in the current window
Update the hashmap as you slide the window to the right and maintain the count of distinct elements
Return the count of distinct elements for each window as an array
Q194. A stream of data is coming. Maintain records in a page and mechanism to see previous and next page. (Concept of Doubly Linked List) (It is always advisable to ask questions in design questions. The interviewers...
read moreA thread is a unit of execution within a process that can run independently and concurrently with other threads.
Threads allow for concurrent execution of tasks within a program.
Threads share the same memory space and resources of the process they belong to.
Threads can communicate and synchronize with each other through shared data structures like locks and semaphores.
Threads can improve performance by utilizing multiple CPU cores or by handling I/O operations asynchronously.
E...read more
Q195. Find Row With Maximum 1's in a Sorted 2D Matrix
You are provided with a 2D matrix containing only the integers 0 or 1. The matrix has dimensions N x M, and each row is sorted in non-decreasing order. Your objec...read more
Find the row with the maximum number of 1's in a sorted 2D matrix.
Iterate through each row of the matrix and count the number of 1's in each row.
Keep track of the row index with the maximum number of 1's encountered so far.
Return the index of the row with the maximum number of 1's.
If multiple rows have the same number of 1's, return the row with the smallest index.
Q196. N Queens Problem
Given an integer N
, find all possible placements of N
queens on an N x N
chessboard such that no two queens threaten each other.
Explanation:
A queen can attack another queen if they are in the...read more
The N Queens Problem involves finding all possible placements of N queens on an N x N chessboard without threatening each other.
Use backtracking algorithm to explore all possible configurations.
Keep track of rows, columns, and diagonals to ensure queens do not threaten each other.
Generate all valid configurations and print them as specified in the output format.
Q197. Time to Burn Tree Problem
You are given a binary tree consisting of 'N' unique nodes and a start node where the burning will commence. The task is to calculate the time in minutes required to completely burn th...read more
Calculate the time in minutes required to completely burn a binary tree starting from a given node.
Start burning from the given node and spread fire to adjacent nodes each minute
Track the time taken for each node to burn and return the maximum time taken
Use a queue to keep track of nodes to be burned next
Q198. LRU Cache Implementation
Design and implement a Least Recently Used (LRU) cache data structure, which supports the following operations:
get(key)
- Return the value of the key if it exists in the cache, otherw...read more
Implement a Least Recently Used (LRU) cache data structure with get and put operations.
Use a combination of a hashmap and a doubly linked list to efficiently implement the LRU cache.
Keep track of the least recently used item and update it accordingly when inserting new items.
Ensure to handle the capacity constraint by evicting the least recently used item when the cache is full.
For get operation, return the value of the key if it exists, otherwise return -1.
Q199. Count Distinct Palindromic Substrings
Given a string STR
, your task is to determine the total number of palindromic substrings present in the string.
Input:
The first line contains an integer 't', representing ...read more
Count the total number of palindromic substrings in a given string.
Iterate through each character in the string and expand around it to find palindromic substrings.
Keep track of the count of palindromic substrings found.
Consider both odd and even length palindromes while expanding around each character.
Q200. Data Structure with Insert, Delete, and GetRandom Operations
Design a data structure that supports four operations: insert an element, remove an element, search for an element, and get a random element. Each op...read more
Design a data structure supporting insert, delete, search, and getRandom operations in constant time.
Use a combination of hashmap and array to achieve O(1) time complexity for each operation.
For insert operation, check if element exists in hashmap, if not add to array and hashmap.
For remove operation, check if element exists in hashmap, if yes, remove from array and hashmap.
For search operation, check if element exists in hashmap.
For getRandom operation, generate a random ind...read more
More about working at Amazon
Top HR Questions asked in SK Patodia
Interview Process at SK Patodia
Top Interview Questions from Similar Companies
Reviews
Interviews
Salaries
Users/Month