
Paytm


400+ Paytm Interview Questions and Answers
Q1. Puzzle : 100 people are standing in a circle .each one is allowed to shoot a person infront of him and he hands the gun to the next to next person for e.g 1st person kills 2nd and hands gun to 3rd .This continu...
read moreA puzzle where 100 people shoot the person in front of them until only one person remains.
Each person shoots the person in front of them and hands the gun to the next to next person.
This continues until only one person remains.
The last person standing is the one who was not shot by anyone.
Q2. Generate Binary Strings with No Consecutive 1s
Given an integer K
, your task is to produce all binary strings of length 'K' that do not contain consecutive '1's.
Input:
The input begins with an integer 'T', the...read more
Generate all binary strings of length 'K' with no consecutive '1's in lexicographically increasing order.
Use backtracking to generate all possible binary strings without consecutive '1's.
Start with an empty string and recursively add '0' or '1' based on the condition.
Keep track of the current string and its length to ensure no consecutive '1's are added.
Sort the generated strings in lexicographically increasing order before outputting.
Q3. Sum of Squares of First N Natural Numbers Problem Statement
You are tasked with finding the sum of squares of the first N
natural numbers for given test cases.
Input:
The first line contains an integer 'T', the...read more
The task is to find the sum of squares of the first 'N' natural numbers.
Iterate from 1 to N and calculate the square of each number
Add all the squares together to get the final sum
Return the sum as the result
Q4. Minimum Number of Coins Problem
Dora, on her visit to India, decides to enjoy Indian cuisine where payments are accepted only in specific denominations. Your task is to help Dora obtain the minimum number of co...read more
Find the minimum number of coins needed to make up a given amount using specific denominations.
Iterate through the available denominations in descending order
For each denomination, calculate the maximum number of coins that can be used
Subtract the total value of coins used from the amount until amount becomes 0
Q5. Reverse Linked List Problem Statement
Given a singly linked list of integers, return the head of the reversed linked list.
Example:
Initial linked list: 1 -> 2 -> 3 -> 4 -> NULL
Reversed linked list: 4 -> 3 -> 2...read more
Reverse a singly linked list of integers and return the head of the reversed linked list.
Iterate through the linked list and reverse the pointers to point to the previous node instead of the next node.
Use three pointers to keep track of the current, previous, and next nodes while reversing the linked list.
Update the head of the reversed linked list as the last node encountered during the reversal process.
Q6. Longest Consecutive Sequence Problem Statement
You are provided with an unsorted array/list ARR
of N
integers. Your task is to determine the length of the longest consecutive sequence present in the array.
Expl...read more
The task is to find the length of the longest consecutive sequence in an unsorted array of integers.
Iterate through the array and store all elements in a set for constant time lookup.
For each element, check if it is the start of a sequence by looking for element-1 in the set.
If it is the start, keep incrementing the count until the next element is not found in the set.
Q7. SpecialStack Design Problem
Design a stack that efficiently supports the getMin() operation in O(1) time with O(1) extra space. This stack should include the following operations: push(), pop(), top(), isEmpty(...read more
Design a stack that supports getMin() operation in O(1) time with O(1) extra space using inbuilt stack data structure.
Use two stacks - one to store the actual data and another to store the minimum value at each level.
When pushing a new element, check if it is smaller than the current minimum and update the minimum stack accordingly.
When popping an element, also pop the top element from the minimum stack if it matches the popped element.
For getMin() operation, simply return th...read more
Q8. Subsequence Determination Problem
Your task is to verify if the given string STR1
is a subsequence of the string STR2
. A subsequence means characters from STR2
are retained in their original order but some (or ...read more
Verify if a string is a subsequence of another string by checking if characters are retained in order.
Iterate through both strings simultaneously, checking if characters match in order.
If a character in STR1 matches a character in STR2, move to the next character in STR2.
If all characters in STR1 are found in STR2 in order, return True; otherwise, return False.
Q9. Search In Rotated Sorted Array Problem Statement
Given a sorted array of distinct integers that has been rotated clockwise by an unknown amount, you need to search for a specified integer in the array. For each...read more
Implement a search function to find a specified integer in a rotated sorted array with O(logN) time complexity.
Implement a binary search algorithm to efficiently search for the target integer.
Handle the rotation of the array by finding the pivot point first.
Return the index of the target integer if found, else return -1.
Ensure the time complexity of the search function is O(logN) for each query.
Q10. Segregate Even and Odd Nodes in a Linked List
You are given the head node of a singly linked list head
. Your task is to modify the linked list so that all the even-valued nodes appear before all the odd-valued ...read more
Reorder a singly linked list so that all even-valued nodes appear before odd-valued nodes while preserving the original order.
Create two separate linked lists for even and odd nodes
Traverse the original list and move nodes to respective even or odd lists
Merge the even and odd lists while maintaining the original order
Q11. 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 through tree T and check if any subtree matches tree S
Use recursion to compare nodes of both trees
Handle edge cases like null nodes and empty trees
Q12. 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 determine the total number of ways to make change for a specified value using given denominations.
Use dynamic programming to keep track of the number of ways to make change for each value up to the target value.
Iterate through each denomination and update the number of ways to make change for each value based on the current denomination.
Handle base cases such as making change for 0 or using only the smallest denomination.
Consider edge cases like having a single...read more
Q13. Minimum Subset Sum Difference Problem
Given an array of non-negative integers, your task is to partition this array into two subsets such that the absolute difference between the sums of the subsets is minimize...read more
Given an array, partition it into two subsets to minimize the absolute difference between their sums.
Use dynamic programming to calculate all possible subset sums.
Iterate through the subset sums to find the minimum absolute difference.
Consider all possible partitions of the array elements.
Example: For input [1, 6, 11, 5], the minimum absolute difference is 1.
Example: For input [1, 2, 3], the minimum absolute difference is 0.
Q14. Ninja Technique Problem Statement
Implement a function that determines whether a given numeric string contains any substring whose integer value equals the product of two consecutive integers. The function shou...read more
Implement a function to determine if a numeric string contains a substring whose value equals the product of two consecutive integers.
Iterate through all substrings of the input string and check if their integer value equals the product of two consecutive integers.
Use nested loops to generate all possible substrings efficiently.
Check if the product of two consecutive integers matches the integer value of the substring.
Return 'True' if any such substring is found, otherwise re...read more
Q15. Find Nodes at a Specific Distance from Target in a Binary Tree
Given a binary tree, a target node within this tree, and an integer K
, identify and return all nodes that are exactly K
edges away from the target ...read more
Find nodes at a specific distance from a target node in a binary tree.
Traverse the binary tree to find the target node.
Perform a depth-first search to identify nodes at distance K from the target node.
Return the values of nodes found at distance K in an array.
Q16. Rotting Oranges Problem Statement
You are given a grid containing oranges where each cell of the grid can contain one of the three integer values:
- 0 - representing an empty cell
- 1 - representing a fresh orange...read more
Find the minimum time required to rot all fresh oranges in a grid.
Use Breadth First Search (BFS) to simulate the rotting process of oranges.
Track the time taken to rot all fresh oranges and return the result.
If any fresh oranges remain after simulation, return -1 as it is impossible to rot all oranges.
Q17. Min Stack Problem Statement
Design a special stack that supports the following operations in constant time:
Push(num)
: Insert the given number into the stack.Pop
: Remove and return the top element from the st...read more
Design a special stack supporting constant time operations like push, pop, top, and getMin.
Implement a stack using an additional stack to keep track of the minimum element.
Use two stacks - one to store elements and another to store minimum values.
Ensure constant time complexity for all operations by maintaining the minimum value at the top of the min stack.
Example: Push(1), Push(2), getMin() should return 1.
Q18. Reverse Alternate K Nodes Problem Statement
You are given a singly linked list of integers along with a positive integer 'K'. The task is to modify the linked list by reversing every alternate 'K' nodes of the ...read more
The task is to modify a singly linked list by reversing every alternate 'K' nodes of the linked list.
Iterate through the linked list in groups of size K, reverse every alternate group
Handle cases where the number of remaining nodes is less than K
Update the pointers accordingly to reverse the nodes in the linked list
Q19. Minimum Falling Path Sum Problem Statement
Given a square array VEC
of integers with N
rows and N
columns, you need to determine the minimum sum of a falling path through this square array. The array has equal ...read more
Find the minimum sum of a falling path through a square array by selecting one element from each row with constraints on column selection.
Iterate through the array from the second row, updating each element with the minimum sum of the element and its adjacent elements from the previous row.
The minimum sum path will end in the last row with the minimum value.
Use dynamic programming to efficiently calculate the minimum falling path sum.
Example: For input [[5, 10], [25, 15]], th...read more
Q20. String Transformation Problem
Given a string (STR
) of length N
, you are tasked to create a new string through the following method:
Select the smallest character from the first K
characters of STR
, remove it fr...read more
Given a string and an integer K, create a new string by selecting the smallest character from the first K characters of the input string and repeating the process until the input string is empty.
Iterate through the input string, selecting the smallest character from the first K characters each time.
Remove the selected character from the input string and append it to the new string.
Continue this process until the input string is empty.
Return the final new string formed.
Q21. Geometric Progression Subsequences Problem Statement
Given an array of ‘N’ integers, determine the number of subsequences of length 3 that form a geometric progression with a specified common ratio ‘R’.
Explana...read more
Count the number of subsequences of length 3 forming a geometric progression with a specified common ratio in an array of integers.
Iterate through the array and for each element, check for possible subsequences of length 3 with the given common ratio.
Use a hashmap to store the count of possible subsequences for each element as the middle element.
Return the total count of subsequences modulo 10^9 + 7.
Example: For input [2, 4, 8, 16] and common ratio 2, the only subsequence [2,...read more
Q22. 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
Group anagrams in an array of strings based on their characters.
Iterate through each string in the input array/list.
For each string, sort the characters alphabetically to create a key for grouping.
Use a hashmap to group strings with the same key.
Return the grouped anagrams as separate arrays of strings.
Q23. Middle of a Linked List
You are given the head node of a singly linked list. Your task is to return a pointer pointing to the middle of the linked list.
If there is an odd number of elements, return the middle ...read more
Return the middle element of a singly linked list, or the one farther from the head node if there are even elements.
Traverse the linked list with two pointers, one moving twice as fast as the other
When the fast pointer reaches the end, the slow pointer will be at the middle
Return the element pointed to by the slow pointer
Q24. Distinct Subsets Count
Given an array arr
of N integers that may include duplicates, determine the number of subsets of this array containing only distinct elements.
The result should be returned modulo 109 + 7...read more
Count the number of distinct-element subsets in an array modulo 10^9+7.
Iterate through the array and keep track of distinct elements using a set.
Calculate the number of subsets using the formula 2^distinct_count - 1.
Return the result modulo 10^9+7 for each test case.
Q25. Sort an Array in Wave Form
You are given an unsorted array ARR
. Your task is to sort it so that it forms a wave-like array.
Input:
The first line contains an integer 'T', the number of test cases.
For each test ...read more
Sort an array in wave form where each element is greater than or equal to its adjacent elements.
Iterate through the array and swap adjacent elements to form a wave pattern.
Ensure that the first element is greater than or equal to the second element.
There can be multiple valid wave arrays, so any valid wave array is acceptable.
Q26. Reverse a Linked List Problem Statement
You are given a Singly Linked List of integers. Your task is to reverse the Linked List by changing the links between nodes.
Input:
The first line of input contains a sin...read more
Reverse a given singly linked list by changing the links between nodes.
Iterate through the linked list and reverse the links between nodes
Use three pointers to keep track of the current, previous, and next nodes
Update the links between nodes to reverse the list
Return the head of the reversed linked list
Q27. Problem: Sort an Array of 0s, 1s, and 2s
Given an array/list ARR
consisting of integers where each element is either 0, 1, or 2, your task is to sort this array in increasing order.
Input:
The input starts with...read more
The task is to sort an array of 0s, 1s, and 2s in increasing order.
Use a three-pointer approach to partition the array into three sections: 0s, 1s, and 2s.
Initialize three pointers: low, mid, and high. low points to the start of the array, mid points to the current element being processed, and high points to the end of the array.
While mid <= high, if ARR[mid] is 0, swap ARR[low] and ARR[mid], increment low and mid. If ARR[mid] is 1, increment mid. If ARR[mid] is 2, swap ARR[m...read more
Q28. Replace 0s Problem Statement
You are given a matrix where every element is either a 1 or a 0. The task is to replace 0 with 1 if it is surrounded by 1s. A 0 (or a set of 0s) is considered to be surrounded by 1s...read more
Given a matrix of 1s and 0s, replace 0s surrounded by 1s with 1s.
Iterate through the matrix and check each 0 surrounded by 1s.
If a 0 is surrounded by 1s, replace it with 1.
Update the matrix in place without printing or returning it.
Q29. Kth Smallest Element Problem Statement
You are provided with an array of integers ARR
of size N
and an integer K
. Your task is to find and return the K
-th smallest value present in the array. All elements in th...read more
Find the K-th smallest element in a given array of distinct integers.
Sort the array in ascending order.
Return the element at index K-1 from the sorted array.
Handle edge cases like K being out of bounds or array being empty.
Q30. Distributing Coins in a Binary Tree
You are provided with the root of a binary tree that consists of 'N' nodes. Each node in this tree contains coins, and the total number of coins across all nodes is equal to ...read more
Determine the minimum number of moves required to distribute coins in a binary tree so that every node has exactly one coin.
Traverse the binary tree in a bottom-up manner to distribute coins efficiently.
Keep track of the excess or deficit of coins at each node to calculate the minimum moves required.
Transfer coins from nodes with excess coins to nodes with deficits to balance the distribution.
Example: For the input ROOT = [2, -1, 0, -1, -1], the output is 1 as one move is nee...read more
Q31. 0-1 Knapsack Problem Statement
A thief is robbing a store and can carry a maximal weight 'W' in his knapsack. There are 'N' items, where the i-th item has a weight 'wi' and value 'vi'. Consider the maximum weig...read more
The 0-1 Knapsack Problem involves maximizing the value of items a thief can steal within a weight limit.
Use dynamic programming to solve the problem efficiently.
Create a 2D array to store the maximum value that can be achieved at each weight limit.
Iterate through the items and weights to fill the array with optimal values.
Return the maximum value achievable at the given weight limit.
Q32. Delete a Node from Linked List Problem Statement
Given a linked list of integers, your task is to implement a function that deletes a node at a specified position, 'POS'.
If the specified position is greater th...read more
Implement a function to delete a node at a specified position in a linked list.
Traverse the linked list to find the node at the specified position.
Update the pointers to skip the node to be deleted.
Handle edge cases like deleting the head or tail node.
Return the modified linked list.
Number In Arithmetic Progression Problem
Given three integers X
, C
, and Y
, where X
is the first term of an arithmetic sequence with a common difference of C
, determine if Y
is part of this arithmetic sequence.
Determine if a given number is part of an arithmetic sequence with a specified first term and common difference.
Calculate the arithmetic sequence based on the given first term and common difference.
Check if the given number is part of the calculated sequence.
Return 'True' if the number belongs to the sequence, otherwise return 'False'.
Q34. Detect and Remove Loop in Linked List
For a given singly linked list, identify if a loop exists and remove it, adjusting the linked list in place. Return the modified linked list.
Expected Complexity:
Aim for a...read more
Detect and remove loop in a singly linked list in place with O(n) time complexity and O(1) space complexity.
Use Floyd's Cycle Detection Algorithm to identify the loop in the linked list.
Once the loop is detected, use two pointers to find the start of the loop.
Adjust the pointers to remove the loop and return the modified linked list.
Q35. Maximum Subarray Sum Problem Statement
Given an array ARR
consisting of N
integers, your goal is to determine the maximum possible sum of a non-empty contiguous subarray within this array.
Example of Subarrays:...read more
The task is to find the maximum possible sum of a non-empty subarray of an array.
Iterate through the array and keep track of the maximum sum encountered so far
If the current element is greater than the sum so far, start a new subarray
If the current element plus the sum so far is greater than the maximum sum, update the maximum sum
Return the maximum sum
Q36. Permutations Problem Statement
Given an array of distinct integers, find all possible permutations of the array.
Explanation:
A permutation is a mathematical way of determining the number of possible arrangemen...read more
Find all possible permutations of an array of distinct integers.
Use backtracking to generate all possible permutations
Swap elements to create different permutations
Return the permutations as an array of arrays of integers
Q37. Decode String Problem Statement
Your task is to decode a given encoded string back to its original form.
Explanation:
An encoded string format is
Decode a given encoded string back to its original form by repeating the encoded string 'count' times.
Parse the input string to extract the count and the encoded string within the brackets
Use recursion to decode the encoded string by repeating it 'count' times
Handle nested brackets by recursively decoding the inner strings first
Q38. 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
The task is to connect N ropes into one rope with minimum cost.
Sort the array of rope lengths in ascending order.
Initialize a variable to keep track of the total cost.
While there are more than one rope, take the two shortest ropes and connect them.
Add the cost of connecting the two ropes to the total cost.
Replace the two shortest ropes with the connected rope.
Repeat the above steps until only one rope remains.
Return the total cost.
Q39. Delete a Node in a Linked List
Given a reference to a node in a singly linked list, your task is to delete that node. Every node in the list has a unique value. The head of the linked list will not be provided....read more
To delete a node in a singly linked list given a reference to the node.
Traverse the linked list to find the node to be deleted.
Update the value of the node to be deleted with the value of the next node.
Point the next pointer of the node to be deleted to the next node's next pointer.
Q40. Smallest Integer Not Representable as Subset Sum
Given a non-decreasing sorted array ARR
of N
positive numbers, determine the smallest positive integer that cannot be expressed as the sum of elements from any p...read more
The task is to find the smallest positive integer value that cannot be represented as a sum of elements of any proper subset of the given array.
The array is sorted in non-decreasing order, so we can iterate through the array and keep track of the maximum sum we can form.
If the current element is greater than the maximum sum + 1, then the maximum sum + 1 is the smallest positive integer that cannot be represented.
If all elements in the array can be represented as a sum of subs...read more
Q41. Factorial Calculation Problem Statement
Develop a program to compute the factorial of a given integer 'n'.
The factorial of a non-negative integer 'n', denoted as n!
, is the product of all positive integers les...read more
Program to compute factorial of a given integer 'n', with error handling for negative values.
Create a function to calculate factorial using a loop or recursion
Check if input is negative, return 'Error' if true
Handle edge cases like 0 and 1 separately
Return the calculated factorial value
Q42. Minimum Number of Platforms Required
You are provided with two arrays, AT
and DT
, representing the arrival and departure times of all trains arriving at a railway station.
Your task is to determine the minimum ...read more
This question asks to find the minimum number of platforms required at a railway station so that no train needs to wait.
Sort the arrival and departure times arrays in ascending order.
Initialize a variable 'platforms' to 1 and 'maxPlatforms' to 1.
Iterate through the arrival and departure times arrays simultaneously.
If the current arrival time is less than or equal to the current departure time, increment 'platforms'.
If 'platforms' is greater than 'maxPlatforms', update 'maxPla...read more
Q43. How will you implement a shuffle function for a playlist of songs
Implementing a shuffle function for a playlist of songs
Create a new empty playlist
Randomly select a song from the original playlist and add it to the new playlist
Remove the selected song from the original playlist
Repeat until all songs have been added to the new playlist
Return the new shuffled playlist
Diameter of a Binary Tree Problem Statement
Given a binary tree, return the length of its diameter. The diameter of a binary tree is defined as the length of the longest path between any two nodes in the tree.
The diameter of a binary tree is the length of the longest path between any two end nodes in the tree.
The diameter of a binary tree can be calculated by finding the maximum of the following three values: 1) the diameter of the left subtree, 2) the diameter of the right subtree, and 3) the longest path that passes through the root node.
To find the diameter of a binary tree, we can use a recursive approach where we calculate the height of each node and update the diameter at ea...read more
Q45. Minimum Fountains Activation Problem
In this problem, you have a one-dimensional garden of length 'N'. Each position from 0 to 'N' has a fountain that can provide water to the garden up to a certain range. Thus...read more
Find the minimum number of fountains to activate to water the entire garden.
Iterate through the array to find the coverage of each fountain.
Keep track of the farthest coverage reached by each activated fountain.
Activate the fountain that covers the farthest distance not yet covered.
Repeat until the entire garden is watered.
Q46. Spiral Order Traversal of a Binary Tree Problem Statement
Given a binary tree with 'N' nodes, your task is to print the nodes in spiral order traversal.
Example:
Input:
The binary tree is represented in level o...read more
Print nodes of a binary tree in spiral order traversal.
Use a queue to perform level order traversal.
Alternate between printing nodes from left to right and right to left at each level.
Handle null nodes appropriately.
Example: For input '1 2 3 -1 -1 4 5 -1 -1 -1 -1', output should be '1 3 2 4 5'.
Q47. Clone Linked List with Random Pointer
Your task is to create a deep copy of a linked list, where each node has two pointers: one that points to the next node in the list, and a 'random' pointer which can point ...read more
Create a deep copy of a linked list with random pointers.
Iterate through the original linked list and create a new node for each node in the list.
Store the mapping of original nodes to their corresponding new nodes in a hashmap.
Iterate through the list again to set the next and random pointers of the new nodes based on the mapping.
Return the head of the newly created deep copied linked list.
Q48. BST Iterator Problem Statement
You are tasked with creating a class named BSTIterator
that acts as an iterator for the inorder traversal of a binary search tree. Implement the following functions:
BSTIterator(...read more
Create a BSTIterator class for inorder traversal of a binary search tree.
Implement a constructor that takes the root of the binary search tree and initializes the iterator.
Implement next() function to return the next smallest element in the inorder traversal.
Implement hasNext() function to check if there is a next element in the inorder traversal.
Traverse the binary search tree in inorder to get the desired output.
Q49. 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 task is to find the number of distinct ways to climb from the 0th step to the Nth step, where each time you can climb either one step or two steps.
Use dynamic programming to solve this problem
Create an array to store the number of ways to reach each step
Initialize the first two elements of the array as 1 and 2
For each subsequent step, the number of ways to reach that step is the sum of the number of ways to reach the previous two steps
Return the number of ways to reach th...read more
Q50. Sub Sort Problem Statement
You are given an integer array ARR
. Determine the length of the shortest contiguous subarray which, when sorted in ascending order, results in the entire array being sorted in ascendi...read more
Determine the length of the shortest contiguous subarray that needs to be sorted to make the entire array sorted in ascending order.
Iterate from left to right to find the first element out of order.
Iterate from right to left to find the last element out of order.
Calculate the length of the subarray between the two out of order elements.
Q51. Inorder Successor in a Binary Tree
Find the inorder successor of a given node in a binary tree. The inorder successor is the node that appears immediately after the given node during an inorder traversal. If th...read more
Find the inorder successor of a given node in a binary tree.
Perform an inorder traversal of the binary tree to find the successor of the given node.
If the given node has a right child, the successor will be the leftmost node in the right subtree.
If the given node does not have a right child, backtrack to the parent nodes to find the successor.
Q52. Parth's OCD Challenge
Parth, a budding programmer, has received an array 'ARR' of 'N' positive integers. His OCD is triggered whenever an odd number appears at an even index or an even number at an odd index in...read more
Reorder array to avoid odd numbers at even indices and even numbers at odd indices.
Swap odd numbers at even indices with the nearest odd number at an odd index.
Swap even numbers at odd indices with the nearest even number at an even index.
Maintain counts of odd and even numbers to ensure equal distribution.
Q53. Cube Sum Pairs Problem Statement
Given a positive integer N
, find the number of ways to express N
as a sum of cubes of two integers, A
and B
, such that:
N = A^3 + B^3
Ensure you adhere to the following conditio...read more
The problem involves finding the number of ways to express a given positive integer as a sum of cubes of two integers.
Iterate through all possible values of A and B within the given constraints.
Check if A^3 + B^3 equals the given N, increment the count if true.
Handle the case where A = B separately to avoid counting duplicates.
Q54. Ceil Value from BST Problem Statement
Given a Binary Search Tree (BST) and an integer, write a function to return the ceil value of a particular key in the BST.
The ceil of an integer is defined as the smallest...read more
Ceil value of a key in a Binary Search Tree (BST) is the smallest integer greater than or equal to the given number.
Traverse the BST to find the closest integer greater than or equal to the given key.
Compare the key with the current node value and update the ceil value accordingly.
Recursively traverse left or right subtree based on the key value to find the ceil value.
Return the ceil value once found for each test case.
Q55. 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
Sort an integer array containing only 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-place.
Time complexity should be O(N) to solve the problem efficiently.
Q56. Delete Middle Node Problem Statement
You are given a singly linked list of integers. The task is to delete the middle node of this list.
Note:
1. If the list has no middle node, return an empty list (NULL). 2. ...read more
Delete the middle node of a singly linked list in O(N) time complexity and O(1) space complexity.
Identify the middle node using slow and fast pointers technique.
Update the pointers to skip the middle node.
Handle edge cases like no middle node or two middle nodes.
Perform the deletion in a single traversal of the linked list.
Return the modified linked list after deletion.
Q57. Bottom Right View of Binary Tree Problem Statement
Your task is to identify and return the bottom right view of a given binary tree.
This involves viewing the binary tree from an angle of 45 degrees from the bo...read more
Identify and return the bottom right view of a given binary tree by viewing it from an angle of 45 degrees from the bottom right side.
Traverse the binary tree in a right-to-left manner and keep track of the last node encountered at each level.
Use a queue for level order traversal and update the result array with the last node at each level.
Return the result array sorted in ascending order as the bottom right view of the binary tree.
Q58. Closest Leaf in a Binary Tree
Ninja is stuck in a maze represented as a binary tree, and he is at a specific node ‘X’. Help Ninja find the shortest path to the nearest leaf node, which is considered an exit poi...read more
Find the minimum distance from a given node to the nearest leaf node in a binary tree.
Traverse the binary tree from the given node 'X' to find the nearest leaf node using BFS or DFS.
Keep track of the distance from 'X' to each leaf node encountered during traversal.
Return the minimum distance found as the output.
Q59. All Pairs with Target Sum
Given an array of integers ARR
with length 'N' and an integer 'Target', the task is to find all unique pairs of elements that add up to the 'Target'.
Input:
First line: Integer 'T' - n...read more
Find all unique pairs of elements in an array that add up to a given target sum.
Use a hashmap to store the difference between the target sum and each element as keys and their indices as values.
Iterate through the array and check if the current element's complement exists in the hashmap.
Return the pairs of elements that add up to the target sum.
Q60. Quick Sort Problem Statement
Sort the given array of integers in ascending order using the quick sort algorithm. Quick sort is a divide-and-conquer algorithm where a pivot point is chosen to partition the array...read more
Implement quick sort algorithm to sort an array of integers in ascending order.
Choose a pivot element (e.g., rightmost element) to partition the array into two subarrays.
Recursively apply quick sort on the subarrays until the entire array is sorted.
Time complexity can be optimized to NlogN for worst-case scenarios.
Q61. 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
Find two lines to form a container with maximum water capacity based on given heights.
Iterate through the array and use two pointers to find the maximum area.
Calculate the area using the formula: min(height[left], height[right]) * (right - left).
Move the pointer with the smaller height towards the center to potentially find a larger area.
Q62. Maze Obstacle Problem Statement
Given an N * M grid representing a maze with obstacles, compute and return the total number of distinct paths from the top-left cell to the bottom-right cell. A cell in the maze ...read more
Find the total number of distinct paths in a maze with obstacles from top-left to bottom-right cell.
Use dynamic programming to keep track of the number of paths to reach each cell.
Handle blocked cells by setting their path count to 0.
Only move right or down from any given cell to calculate the number of paths.
Return the total number of valid paths modulo 10^9 + 7.
Q63. Minimize Cash Flow Problem
You are provided with a list of 'transactions' involving 'n' friends who owe each other money. Each entry in the list contains information about a receiver, sender, and the transactio...read more
Minimize cash flow among friends by optimizing transactions.
Create a graph where nodes represent friends and edges represent transactions.
Calculate net amount each friend owes or is owed by summing up all transactions.
Use a recursive algorithm to minimize cash flow by settling debts between friends.
Update the graph after each settlement and continue until all debts are settled.
Output the minimized cash flow in a 2-D matrix for each test case.
Q64. 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
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 this problem efficiently.
Iterate through the strings and build a matrix to store the lengths of common subsequences.
The value in the bottom-right corner of the matrix will be the length of the longest common subsequence.
Q65. Group Anagrams Together
Given an array/list of strings STR_LIST
, group the anagrams together and return each group as a list of strings. Each group must contain strings that are anagrams of each other.
Example:...read more
Group anagrams together in a list of strings.
Iterate through the list of strings and sort each string to group anagrams together.
Use a hashmap to store the sorted string as key and the original string as value.
Return the values of the hashmap as the grouped anagrams.
Q66. Job Sequencing Problem Statement
You are provided with a N x 2 2-D array called Jobs
consisting of N
jobs. In this array, Jobs[i][0]
represents the deadline of the i-th job, while Jobs[i][1]
indicates the profi...read more
Maximize profit by scheduling jobs within their deadlines.
Sort the jobs array in descending order of profits.
Iterate through the sorted array and schedule jobs based on deadlines.
Keep track of completed jobs and their profits to calculate the total profit.
Return the maximum profit achieved by scheduling jobs within deadlines.
Q67. 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
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.
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 of the larger heap. If even, average the tops of both heaps.
Q68. Next Greater Element Problem Statement
Given a list of integers of size N
, your task is to determine the Next Greater Element (NGE) for every element. The Next Greater Element for an element X
is the first elem...read more
The task is to find the Next Greater Element for each element in a list of integers.
Iterate through the list of integers from right to left
Use a stack to keep track of elements whose NGE is yet to be found
Pop elements from the stack until a greater element is found or the stack is empty
Assign the NGE as the top element of the stack or -1 if the stack is empty
Q69. Cousin Nodes in a Binary Tree
Determine if two nodes in a binary tree are cousins. Nodes are considered cousins if they are at the same level and have different parents.
Explanation:
In a binary tree, each node...read more
Determine if two nodes in a binary tree are cousins based on level and parent nodes.
Traverse the binary tree to find the levels and parents of the given nodes.
Check if the nodes are at the same level and have different parents to determine if they are cousins.
Return 'YES' if the nodes are cousins, 'NO' otherwise.
Example: For input '1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1' and nodes 4 7, output is 'YES'.
Q70. Adding Two Linked Lists
Given two singly linked lists, with each list representing a positive number without leading zeros, your task is to add these two numbers and return the result in the form of a new linke...read more
Add two numbers represented by linked lists and return the result as a new linked list.
Traverse both linked lists simultaneously while adding corresponding elements and carry over the sum if needed
Handle cases where one linked list is longer than the other
Create a new linked list to store the sum of the two numbers
Q71. Merge Sort Task
Given a sequence of numbers, denoted as ARR
, your task is to return a sorted sequence of ARR
in non-descending order using the Merge Sort algorithm.
Example:
Explanation:
The Merge Sort algorith...read more
Implement Merge Sort algorithm to sort a sequence of numbers in non-descending order.
Implement the Merge Sort algorithm which involves dividing the array into two halves, sorting each half, and then merging them back together.
Recursively call the Merge Sort function on each half of the array until the base case of having a single element in the array is reached.
Merge the sorted halves back together in a new array in non-descending order.
Ensure to handle the edge cases such as...read more
Q72. Zigzag Traversal of Binary Tree
Given a binary tree with integer values in its nodes, your task is to print the zigzag traversal of the tree.
Note:
In zigzag order, level 1 is printed from left to right, level ...read more
Implement a function to print the zigzag traversal of a binary tree.
Use a queue to perform level order traversal of the binary tree.
Maintain a flag to switch between printing nodes from left to right and right to left at each level.
Store nodes at each level in a list and reverse the list if the flag is set to print in zigzag order.
Q73. How many BSTs are possible with two nodes and three nodes?
Number of possible BSTs with 2 and 3 nodes.
For 2 nodes, only 2 BSTs are possible.
For 3 nodes, 5 BSTs are possible.
Number of BSTs can be calculated using Catalan numbers formula.
Catalan(2) = 2, Catalan(3) = 5.
Q74. Minimum Insertions to Make a String Palindrome
Determine the minimal number of characters needed to insert into a given string STR
to transform it into a palindrome.
Example:
Input:
STR = "abcaa"
Output:
2
Expl...read more
The task is to find the minimum number of characters needed to insert into a given string to make it a palindrome.
Use dynamic programming to find the longest palindromic subsequence of the given string.
Subtract the length of the longest palindromic subsequence from the length of the original string to get the minimum insertions required.
Handle edge cases like an empty string or a string that is already a palindrome.
Example: For input 'abcaa', the longest palindromic subsequen...read more
Q75. Odd Even Levels in Binary Tree
Given a binary tree, the task is to compute the modulus of the difference between the sum of nodes at odd levels and the sum of nodes at even levels.
Input:
The first line contain...read more
The task is to compute the modulus of the difference between the sum of nodes at odd levels and the sum of nodes at even levels in a binary tree.
Traverse the binary tree level by level and calculate the sum of nodes at odd and even levels separately.
Find the absolute difference between the sums and return the modulus of this difference.
Handle null nodes by skipping them during the sum calculation.
Q76. Minimum Characters to Make a String Palindrome
Given a string STR
of length N
, determine the minimum number of characters to be added to the front of the string to make it a palindrome.
Input:
The first line co...read more
The task is to find the minimum number of characters needed to be added to the front of a string to make it a palindrome.
Iterate through the string from both ends and count the number of characters that need to be added to make it a palindrome.
Use two pointers approach to compare characters from start and end of the string.
Keep track of the count of characters needed to be added to form a palindrome.
Q77. a unsorted array was given and a number x.find out the two elements whose sum is equal to x
Find two elements in an unsorted array whose sum is equal to a given number x.
Use a hash table to store the difference between x and each element in the array.
Iterate through the array and check if the current element is in the hash table.
Return the pair of elements that add up to x.
Q78. Lexicographically Smallest Array Problem Statement
You are given an array ARR
of 'N' integers and a positive integer 'K'.
Your task is to determine the lexicographically smallest array that can be obtained by p...read more
The task is to determine the lexicographically smallest array that can be obtained by performing at most 'K' swaps of consecutive elements.
Sort the array in non-decreasing order and keep track of the number of swaps made.
Iterate through the array and swap adjacent elements if it results in a lexicographically smaller array.
Continue swapping until the maximum number of swaps 'K' is reached or the array is lexicographically smallest.
Return the final lexicographically smallest a...read more
Q79. What is my favourite app and any improvements in it which i want to implement?
My favourite app is Spotify. I would like to see improvements in the algorithm for personalized playlists.
Improved algorithm for personalized playlists
Better integration with social media platforms
Option to create collaborative playlists with friends
Q80. Rotate Matrix by 90 Degrees Problem Statement
Given a square matrix 'MATRIX' of non-negative integers, rotate the matrix by 90 degrees in an anti-clockwise direction using only constant extra space.
Input:
The ...read more
Rotate a square matrix by 90 degrees in an anti-clockwise direction using constant extra space.
Iterate through each layer of the matrix from outer to inner layers
Swap elements in groups of 4 to rotate the matrix
Handle odd-sized matrices by adjusting the center element if needed
Q81. Colorful Knapsack Problem
You are given a set of 'N' stones, each with a specific weight and color. The goal is to fill a knapsack with exactly 'M' stones, choosing one stone of each color, so that the total we...read more
The Colorful Knapsack Problem involves selecting one stone of each color to fill a knapsack with a given weight capacity, minimizing unused capacity.
Iterate through the stones and keep track of the minimum weight for each color.
Use dynamic programming to find the optimal solution by considering all possible combinations.
Handle cases where the knapsack cannot be filled under the given conditions by returning -1.
In the given example, the optimal solution is to select stones wit...read more
Q82. LCA in a Binary Search Tree
You are given a binary search tree (BST) containing N nodes. Additionally, you have references to two nodes, P and Q, within this BST.
Your task is to determine the Lowest Common Anc...read more
Find the Lowest Common Ancestor (LCA) of two nodes in a Binary Search Tree (BST).
Traverse the BST from the root node to find the LCA of the given nodes.
Compare the values of the nodes with the values of P and Q to determine the LCA.
If the values of P and Q are on opposite sides of the current node, then the current node is the LCA.
Q83. House Robber Problem Statement
Mr. X is a professional robber with a plan to rob houses arranged in a circular street. Each house has a certain amount of money hidden, separated by a security system that alerts...read more
The task is to find the maximum amount of money Mr. X can rob from houses arranged in a circle without alerting the police.
The problem can be solved using dynamic programming.
Create two arrays to store the maximum amount of money robbed when considering the first house and when not considering the first house.
Iterate through the array and update the maximum amount of money robbed at each house.
The final answer will be the maximum of the last element in both arrays.
LRU cache in a database management system stores most recently used data and removes least recently used data when full.
LRU cache is implemented using a doubly linked list and a hash map.
Each node in the linked list represents a key-value pair.
When a key is accessed, it is moved to the front of the linked list.
If the cache is full, the least recently used node at the end of the list is removed.
Example: If cache size is 3 and keys accessed in order are A, B, C, D, A, then afte...read more
Q85. two arrays of arrival time of trains and departure time of trains were given. find the minimum no of platforms require so that no collision occurs
Find minimum no of platforms required to avoid collision between trains based on their arrival and departure times.
Sort both arrays in ascending order
Initialize platform count and max count to 1
Loop through both arrays and compare arrival and departure times
If arrival time is less than or equal to departure time, increment platform count
Else, decrement platform count
Update max count if platform count is greater than max count
Return max count
Q86. Find Subarray with Given Sum
Given an array ARR
of N
integers and an integer S
, determine if there exists a subarray (of positive length) within the given array such that the sum of its elements equals S
. If su...read more
Given an array and a target sum, find a subarray that sums up to the target sum.
Iterate through the array while keeping track of the running sum and the starting index of the subarray.
Use a hashmap to store the running sum and its corresponding index.
If the running sum - target sum is found in the hashmap, it means a subarray with the target sum exists.
Return the starting and ending indices of the subarray or [-1, -1] if no such subarray exists.
Q87. Find All Occurrences in Matrix
You are provided with a matrix of characters, CHARACTER_MATRIX
of size M x N
, and a string WORD
. Your goal is to locate and display all occurrences of the string within the matrix...read more
Find all occurrences of a given string in a matrix in all eight possible directions.
Iterate through each cell in the matrix and check for the starting character of the word.
For each starting character found, check in all eight directions for the complete word.
Keep track of the coordinates of each character in the word for each occurrence.
Print the coordinates of each character for all occurrences found.
If no occurrences are found, output 'No match found'.
Q88. Diagonal Traversal of a Binary Tree
Given a binary tree of integers, find its diagonal traversal. Refer to the example for clarification on diagonal traversal.
Example:
Explanation:
Consider lines at an angle o...read more
Find the diagonal traversal of a binary tree of integers.
Traverse the binary tree diagonally using a queue and a map to store nodes at each diagonal level.
Use a depth-first search approach to traverse the tree and populate the map with nodes at each diagonal level.
Iterate through the map to get the diagonal traversal of the binary tree.
Q89. Buy and Sell Stock Problem Statement
Imagine you are Harshad Mehta's friend, and you have been given the stock prices of a particular company for the next 'N' days. You can perform up to two buy-and-sell transa...read more
Given stock prices for 'N' days, find maximum profit with up to two buy-and-sell transactions.
Iterate through the array of stock prices to find the maximum profit with two transactions
Keep track of the maximum profit by considering all possible buy and sell combinations
Ensure to sell the stock before buying again to maximize profit
Q90. Floor Value of X Problem Statement
Given a sorted array A
and an integer X
, your task is to find and return the floor value of X
in the array.
The floor value of X
is the largest element in array A
which is sma...read more
Find the largest element in a sorted array smaller than or equal to a given integer X.
Use binary search to efficiently find the floor value of X in the sorted array.
Compare the middle element of the array with X and adjust the search accordingly.
Return the element before or equal to X as the floor value, or -1 if no such element exists.
Q91. How many trees are possible with two and three nodes?
Answering the question about possible trees with two and three nodes.
For two nodes, there is only one possible tree.
For three nodes, there are three possible trees.
The formula for calculating the number of possible trees with n nodes is (2n-3)!!.
The double exclamation mark represents the double factorial function.
The double factorial function is defined as n!! = n(n-2)(n-4)...(1 or 2).
Q92. LRU Cache Design Question
Design a data structure for a Least Recently Used (LRU) cache that supports the following operations:
1. get(key)
- Return the value of the key if it exists in the cache; otherwise, re...read more
Design a Least Recently Used (LRU) cache data structure that supports get and put operations with a given capacity.
Implement a doubly linked list to keep track of the order of keys based on their recent usage.
Use a hashmap to store key-value pairs for quick access and updates.
When capacity is reached, evict the least recently used item before inserting a new one.
Update the order of keys in the linked list whenever a key is accessed or updated.
Q93. 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
Find the Kth smallest and largest elements in an array.
Sort the array to easily find the Kth smallest and largest elements.
Ensure K is within the array's size to avoid errors.
Handle multiple test cases efficiently.
Consider edge cases like when N is small or K is at the extremes.
Q94. 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
Given a sorted N * N matrix, find the position of a target integer 'X'.
Iterate over rows and columns to search for the target integer 'X'.
Utilize the sorted nature of the matrix to optimize the search process.
Return the position of 'X' if found, else return '-1 -1'.
Q95. Problem Statement: Parity Move
You have an array of integers, and your task is to modify the array by moving all even numbers to the beginning while placing all odd numbers at the end. The order within even and...read more
Move all even numbers to the beginning and odd numbers to the end of an array.
Iterate through the array and swap even numbers to the front and odd numbers to the back.
Use two pointers, one starting from the beginning and one from the end, to achieve the desired arrangement.
Return the modified array with even numbers at the start and odd numbers at the end.
Q96. 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
Determine if two strings are anagrams of each other by checking if they have the same characters in different order.
Create a character frequency map for both strings and compare them.
Sort both strings and compare if they are equal.
Use a hash table to store character counts and check if they are the same for both strings.
Q97. Find the Longest Palindromic Substring
Given a string ‘S’ composed of lowercase English letters, your task is to identify the longest palindromic substring within ‘S’.
If there are multiple longest palindromic ...read more
Find the longest palindromic substring in a given string, returning the rightmost one if multiple exist.
Iterate through each character in the string and expand around it to find palindromes
Keep track of the longest palindrome found and its starting index
Return the substring starting from the index of the longest palindrome found
Q98. Rahul And Minimum Subarray Challenge
Rahul is learning about arrays and lists. His teacher gave him a task to find the length of the smallest subarray in a given array 'ARR' of size 'N' with its sum greater tha...read more
Find the length of the smallest subarray in a given array with sum greater than a given value.
Iterate through the array while keeping track of the current subarray sum.
Use two pointers technique to find the smallest subarray with sum greater than X.
Update the minimum subarray length as you iterate through the array.
Return the length of the smallest subarray found.
Example: For ARR = [1, 2, 21, 7, 6, 12] and X = 23, the output is 2.
Q99. Do you know how market accept the new product?
Market acceptance of new product depends on various factors such as product features, pricing, competition, and marketing strategies.
Conducting market research to understand customer needs and preferences
Analyzing competitor products and pricing strategies
Developing effective marketing campaigns to create awareness and generate interest
Offering competitive pricing and attractive promotions
Collecting feedback from early adopters and making necessary improvements
Monitoring sale...read more
Q100. Find the row with max number of vowels in a 2×2 matrix. Given that first element of each row contains a vowel if there are any in the whole row.
Find row with max vowels in 2x2 matrix with first element of each row containing a vowel.
Iterate through each row and count the number of vowels in it.
Keep track of the row with max number of vowels.
If first element of a row is a vowel, start counting from that element.
Example: [['a', 'b'], ['e', 'i']] should return 2nd row.
Top HR Questions asked in Paytm
Interview Process at Paytm

Top Interview Questions from Similar Companies








Reviews
Interviews
Salaries
Users/Month

