PayPal
100+ Diversitech General Engineering Interview Questions and Answers
Q1. Cycle Detection in a Singly Linked List
Determine if a given singly linked list of integers forms a cycle or not.
A cycle in a linked list occurs when a node's next
points back to a previous node in the list. T...read more
Detect if a singly linked list forms a cycle by checking if a node's next points back to a previous node.
Traverse the linked list using two pointers, one moving one step at a time and the other moving two steps at a time.
If the two pointers meet at any point, it indicates the presence of a cycle in the linked list.
If one of the pointers reaches the end of the list (null), it means there is no cycle.
Q2. Painting Fences Problem Statement
You are given ‘N’ fences. Your task is to compute the total number of ways to paint these fences using only 2 colors, such that no more than 2 adjacent fences have the same col...read more
The task is to compute the total number of ways to paint 'N' fences using 2 colors, such that no more than 2 adjacent fences have the same color.
Use dynamic programming to solve the problem efficiently.
Consider two cases: when the last two fences have the same color and when they have different colors.
Implement a solution that calculates the number of ways to paint 'N' fences modulo 10^9 + 7.
For N = 2, there are 4 valid ways to paint the fences: [0, 1], [1, 0], [1, 1], and [0...read more
Q3. Cycle Detection in Undirected Graph Problem Statement
You are provided with an undirected graph containing 'N' vertices and 'M' edges. The vertices are numbered from 1 to 'N'. Your objective is to determine whe...read more
Detect cycles in an undirected graph with given vertices and edges.
Use Depth First Search (DFS) to traverse the graph and detect cycles.
Maintain a visited array to keep track of visited vertices and a parent array to keep track of the parent of each vertex.
If while traversing, you encounter a visited vertex that is not the parent of the current vertex, then a cycle exists.
Consider edge cases like disconnected graphs and self-loops.
Q4. 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.
Keep track of the previous, current, and next nodes while reversing the linked list.
Update the head of the reversed linked list as the last node encountered during reversal.
Q5. Cycle Detection in a Directed Graph
Determine if a given directed graph contains a cycle. Return true
if at least one cycle is found, otherwise return false
.
Input:
T
The first line consists of the integer T, re...read more
Detect if a directed graph contains a cycle.
Use depth-first search (DFS) to detect cycles in the graph.
Maintain a visited array to keep track of visited vertices.
If a vertex is visited again during DFS and it is not the parent of the current vertex, then a cycle exists.
Return true if a cycle is found, false otherwise.
Q6. Integer to Roman Conversion
Given an integer N
, convert it to its corresponding Roman numeral representation. Roman numerals comprise seven symbols: I, V, X, L, C, D, and M.
Example:
Input:
N = 2
Output:
II
Exp...read more
Convert an integer to its corresponding Roman numeral representation.
Create a mapping of integer values to Roman numeral symbols
Iterate through the mapping in descending order of values and build the Roman numeral representation
Handle special cases like 4, 9, 40, 90, 400, 900 separately
Repeat the process for each digit of the input integer
Q7. Sum Queries in a Sorted Array
Given two arrays arr
and queries
, your task is to determine the sum of all elements in arr
that are less than or equal to each element in queries
. The array arr
is provided in sort...read more
Find sum of elements in a sorted array less than or equal to each element in queries.
Iterate through queries and for each query, find the sum of elements in arr less than or equal to the query element.
Use binary search to efficiently find the index of the last element less than or equal to the query element.
Keep track of cumulative sum while iterating through arr to avoid recalculating sums.
Return the list of sums for each test case.
Q8. Find All Pairs Adding Up to Target
Given an array of integers ARR
of length N
and an integer Target
, your task is to return all pairs of elements such that they add up to the Target
.
Input:
The first line conta...read more
The task is to find all pairs of elements in an array that add up to a given target.
Iterate through the array and for each element, check if the difference between the target and the element exists in a hash set.
If it exists, add the pair to the result. If not, add the element to the hash set.
Handle cases where the same element is used twice in a pair.
Return (-1, -1) if no pair is found.
Q9. Merge Sort Problem Statement
You are given a sequence of numbers, ARR
. Your task is to return a sorted sequence of ARR
in non-descending order using the Merge Sort algorithm.
Explanation:
The Merge Sort algorit...read more
Implement Merge Sort algorithm to sort a sequence of numbers in non-descending order.
Implement the Merge Sort algorithm using a Divide and Conquer approach
Recursively divide the input array into two halves until the size of each array is 1
Merge the sorted halves to produce a completely sorted array
Ensure the output is in non-descending order
Q10. Design a Constant Time Data Structure
Create a data structure that maintains mappings between keys and values, supporting the following operations in constant time:
1. INSERT(key, value): Add or update the inte...read more
Design a constant time data structure for key-value mappings with operations like INSERT, DELETE, SEARCH, GET, GET_SIZE, and IS_EMPTY.
Use a hash table to store key-value pairs for constant time operations.
Implement INSERT by hashing the key and storing the value at the corresponding index.
For DELETE, simply remove the key-value pair from the hash table.
SEARCH can be done by checking if the key exists in the hash table.
GET retrieves the value associated with the key, returning...read more
Q11. Painter's Partition Problem
You are given an array/list of length 'N'. Each element of the array/list represents the length of a board. There are 'K' painters available to paint these boards. Each unit of a boa...read more
Find the minimum time required for 'K' painters to paint 'N' boards with given lengths.
Use binary search to find the minimum and maximum possible time to paint all boards.
Iterate through the possible time range and check if it is feasible to paint all boards within that time.
Keep track of the number of painters used and update the time range accordingly.
Q12. 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 that can be obtained from a path in a matrix from the first row to the last row.
Use dynamic programming to keep track of the maximum sum at each cell in the matrix.
Start from the second row and update each cell with the maximum sum from the cell above and diagonally above left or right.
The maximum sum at the last row will be the answer for each test case.
Q13. Reverse the String Problem Statement
You are given a string STR
which contains alphabets, numbers, and special characters. Your task is to reverse the string.
Example:
Input:
STR = "abcde"
Output:
"edcba"
Input...read more
Reverse a given string containing alphabets, numbers, and special characters.
Iterate through the string from the end to the beginning and append each character to a new string.
Use built-in functions like reverse() or slicing to reverse the string.
Handle special characters and numbers while reversing the string.
Ensure to consider the constraints on the input string length and number of test cases.
Q14. Total Area of Overlapping Rectangles Problem Statement
Determine the total area covered by two given rectangles on a 2-D coordinate plane, which may have an overlapping area.
Input:
The first line contains an i...read more
Calculate the total area covered by two overlapping rectangles on a 2-D coordinate plane.
Parse input coordinates for two rectangles
Calculate the area of each rectangle
Find the overlapping area by determining the intersection of the rectangles
Calculate the total area by adding the areas of both rectangles and subtracting the overlapping area
Q15. Longest Repeating Subsequence Problem Statement
Given a string st
, your task is to determine the length of the longest repeating subsequence such that no two subsequences have the same character at the same pos...read more
The task is to find the length of the longest repeating subsequence in a string with no same characters at the same position.
Iterate through the string and find the longest repeating subsequence by comparing characters at different positions.
Use dynamic programming to keep track of the longest repeating subsequence found so far.
Ensure that no two subsequences have the same character at the same position.
Example: For input 'AABCBDC', the longest repeating subsequence is 'ABC' ...read more
Q16. Find Magic Index in Sorted Array
Given a sorted array A consisting of N integers, your task is to find the magic index in the given array, where the magic index is defined as an index i such that A[i] = i.
Exam...read more
Find the magic index in a sorted array where A[i] = i.
Iterate through the array and check if A[i] = i for each index i
Utilize binary search for a more efficient solution
Handle cases where there are multiple magic indices or none at all
Q17. Palindrome Partitioning II Problem Statement
Given a string ‘str’, find the minimum number of partitions needed such that every segment of the string is a palindrome.
The task is to make cuts in the string to p...read more
Find the minimum number of partitions needed in a string such that every segment is a palindrome.
Iterate through the string and check for palindromes at each possible partition point.
Use dynamic programming to keep track of the minimum cuts needed.
Consider edge cases where the string is already a palindrome or consists of different characters only.
Q18. Maximum Difference Problem Statement
Given an array ARR
of N
elements, your task is to find the maximum difference between any two elements in ARR
.
If the maximum difference is even, print EVEN; if it is odd, p...read more
Find the maximum difference between any two elements in an array and determine if it is even or odd.
Iterate through the array to find the maximum and minimum elements
Calculate the difference between the maximum and minimum elements
Check if the difference is even or odd and return the result
Q19. DFS Traversal Problem Statement
Given an undirected and disconnected graph G(V, E)
, where V
is the number of vertices and E
is the number of edges, the connections between vertices are provided in the 'GRAPH' m...read more
DFS traversal problem on an undirected and disconnected graph to find connected components.
Perform Depth First Search (DFS) on each vertex to find connected components
Use a visited array to keep track of visited vertices
Print the number of connected components and list vertices in ascending order for each component
Q20. Minimum Character Deletion Problem Statement
You have been provided a string STR
. Your task is to find and return the minimum number of characters that need to be deleted from STR
so that each character's frequ...read more
Find the minimum number of character deletions needed to make each character's frequency unique in a given string.
Iterate through the string and count the frequency of each character.
Identify characters with the same frequency and calculate the minimum deletions needed to make them unique.
Return the total minimum deletions for each test case.
Q21. Count Ways To Reach The N-th Stair Problem Statement
You are given a number of stairs, N
. Starting at the 0th stair, you need to reach the Nth stair. Each time you can either climb one step or two steps. You ha...read more
The problem involves finding the number of distinct ways to climb to the N-th stair by taking one or two steps at a time.
Use dynamic programming to solve this problem efficiently.
The number of ways to reach the N-th stair is the sum of the number of ways to reach the (N-1)th stair and the (N-2)th stair.
Handle large inputs by taking modulo 10^9+7 of the result.
Example: For N=3, there are 3 ways to climb to the third stair: (0, 1, 2, 3), (0, 2, 3), and (0, 1, 3).
Q22. One Away Transformation Problem
Given two strings, A
and B
, determine whether A
can be transformed into B
by performing at most one of the following operations (including zero operations):
1. Delete a character...read more
Determine if one string can be transformed into another by performing at most one operation (insert, delete, replace).
Iterate through both strings simultaneously and check for differences.
Handle cases where a character needs to be inserted, deleted, or replaced.
Keep track of the number of operations performed and ensure it does not exceed one.
Q23. 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 values in an array.
Sort the array based on actual values.
Update the linked list with the sorted values.
Q24. 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 where no two queens threaten 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 valid configurations recursively and backtrack when a solution is not possible.
Q25. Friends Pairing Problem
The task is to determine the total number of ways to pair up 'N' friends or leave some of them single, following these rules:
- Each friend can either pair with one other friend or stay s...read more
The task is to determine the total number of ways to pair up 'N' friends or leave some of them single.
Use dynamic programming to solve the problem efficiently.
Consider the base cases when N is 1, 2, and 3 to derive the general formula.
The result should be computed modulo 10^9 + 7 to handle large outputs.
Q26. Counting Sort Problem Statement
Ninja is learning about sorting algorithms, specifically those that do not rely on comparisons. Can you help Ninja implement the counting sort algorithm?
Example:
Input:
ARR = {-...read more
Implement counting sort algorithm to sort an array of integers without comparisons.
Count the frequency of each element in the input array.
Calculate the prefix sum of frequencies to determine the position of each element in the sorted array.
Place each element in its correct position based on the prefix sum.
Time complexity of counting sort is O(n+k), where n is the number of elements and k is the range of input.
Example: Input: ARR = {-2, 1, 2, -1, 0}, Output: {-2, -1, 0, 1, 2}
Q27. K Largest Elements Problem Statement
Given an unsorted array containing 'N' integers, you are required to find 'K' largest elements from the array and return them in non-decreasing order.
Input:
The first line ...read more
Find K largest elements in an unsorted array and return them in non-decreasing order.
Sort the array in non-decreasing order.
Return the last K elements of the sorted array.
Q28. Input a file. Select first 3 lines of the file. Select the longest line and count the number of words in that line. It was easy. I used Java methods to solve the problem. I explained the logic and he accepted i...
read moreThe program reads a file and selects the first 3 lines. It then identifies the longest line and counts the number of words in that line.
Read the file using appropriate file handling methods
Store the first 3 lines in an array of strings
Iterate through the array to find the longest line
Count the number of words in the longest line using string manipulation methods
Q29. Kth Largest Element Problem
Given an array containing N
distinct positive integers and a number K
, determine the Kth largest element in the array.
Example:
Input:
N = 6, K = 3, array = [2, 1, 5, 6, 3, 8]
Output...read more
Find the Kth largest element in an array of distinct positive integers.
Sort the array in non-increasing order and return the Kth element.
Handle multiple test cases efficiently.
Ensure all elements in the array are distinct.
Q30. Next Greater Element Problem Statement
You are given an array arr
of length N
. For each element in the array, find the next greater element (NGE) that appears to the right. If there is no such greater element, ...read more
The task is to find the next greater element for each element in an array to its right, if no greater element exists, return -1.
Use a stack to keep track of elements for which the next greater element is not found yet.
Iterate through the array from right to left and pop elements from the stack until a greater element is found.
Store the next greater element for each element in a separate array.
If the stack is empty after iterating through the array, it means there is no greate...read more
Q31. 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
Sort an array of 0s, 1s, and 2s in increasing order.
Use a three-pointer approach to partition the array into sections of 0s, 1s, and 2s.
Iterate through the array and swap elements based on their values to achieve the sorting.
Time complexity should be O(N) where N is the number of elements in the array.
Q32. Reverse Only Letters Problem Statement
You are given a string S
. The task is to reverse the letters of the string while keeping non-alphabet characters in their original position.
Example:
Input:
S = "a-bcd"
Ou...read more
Reverse the letters of a string while keeping non-alphabet characters in their original position.
Iterate through the string and store the non-alphabet characters in their original positions.
Reverse the letters of the string using two pointers approach.
Combine the reversed letters with the non-alphabet characters to get the final reversed string.
Q33. Balanced Parentheses Combinations
Given an integer N
representing the number of pairs of parentheses, find all the possible combinations of balanced parentheses using the given number of pairs.
Explanation:
Con...read more
Generate all possible combinations of balanced parentheses for a given number of pairs.
Use backtracking to generate all possible combinations of balanced parentheses.
Keep track of the number of open and close parentheses used in each combination.
Recursively generate combinations by adding open parentheses if there are remaining, and closing parentheses if the number of open parentheses is greater than the number of close parentheses.
Return the list of valid combinations as an...read more
Q34. But amazon can do the search in O(n). Why it has to go for O(nk)? For data structures like Hash tables and for large data, n will be large. So O(nk) is better than O(n) (former n is smaller than latter n).
O(nk) is better than O(n) for large data and hash tables.
O(nk) is better because it takes into account the size of the data and the number of keys.
For large data and hash tables, the size of n will be large, making O(nk) more efficient.
O(n) assumes a constant number of keys, which may not be the case in practice.
Amazon may have chosen O(nk) for better scalability and performance.
Q35. Left View of a Binary Tree
Given a binary tree, your task is to print the left view of the tree. The left view of a binary tree contains the nodes visible when the tree is viewed from the left side.
Input:
The ...read more
The task is to print the left view of a binary tree, which contains the nodes visible when the tree is viewed from the left side.
Traverse the tree level by level and keep track of the leftmost node at each level
Use a queue for level order traversal and a map to store the leftmost nodes
Print the values of the leftmost nodes stored in the map as the left view of the tree
Q36. Palindrome Checker Problem Statement
Given an alphabetical string S
, determine whether it is a palindrome or not. A palindrome is a string that reads the same backward as forward.
Input:
The first line of the i...read more
Check if a given string is a palindrome or not.
Iterate through the string from both ends and compare characters.
If all characters match, return 1 indicating a palindrome.
If any characters don't match, return 0 indicating not a palindrome.
Q37. Rearrange String Problem Statement
Given a string ‘S’, your task is to rearrange its characters so that no two adjacent characters are the same. If it's possible, return any such arrangement, otherwise return “...read more
Given a string, rearrange its characters so that no two adjacent characters are the same. Return 'Yes' if possible, 'No' otherwise.
Iterate through the string and count the frequency of each character
Use a priority queue to rearrange characters based on frequency
Check if the rearranged string has no two adjacent characters the same
Return 'Yes' if possible, 'No' otherwise
Q38. 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 in a list of strings together and return each group as a list of strings.
Iterate through the list of strings and sort each string alphabetically to create a key for grouping.
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.
Q39. Divide Two Integers Problem Statement
You are given two integers dividend
and divisor
. Your task is to divide the integers without using multiplication, division, and modular operators. Return the quotient afte...read more
Divide two integers without using multiplication, division, and modular operators, returning the floored value of the quotient.
Implement division using bit manipulation and subtraction
Handle edge cases like negative numbers and overflow
Return the floored value of the quotient
Q40. Find The Sum Of The Left Leaves Problem Statement
Given a binary tree with ‘root’, your task is to find and return the sum of all the left leaf nodes.
Example:
Input:
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
Outpu...read more
Find and return the sum of all the left leaf nodes in a binary tree.
Traverse the binary tree using depth-first search (DFS)
Check if a node is a leaf node and a left child
Sum up the values of all left leaf nodes
Q41. Median of Two Sorted Arrays
Given two sorted arrays A
and B
of sizes N
and M
, find the median of the merged array formed by combining arrays A
and B
. If the total number of elements, N + M
, is even, the median ...read more
Find the median of two sorted arrays by merging them and calculating the median of the combined array.
Merge the two sorted arrays into one sorted array.
Calculate the median of the combined array based on the total number of elements.
Return the median as the result.
Q42. Minimum Cost Path Problem Statement
Given an N x M
matrix filled with integers, determine the minimum sum obtainable from a path that starts at a specified cell (x, y)
and ends at the top left corner of the mat...read more
The problem involves finding the minimum sum path from a specified cell to the top left corner of a matrix.
Start from the specified cell and calculate the minimum sum path to reach the top left corner using dynamic programming.
Consider the three possible moves: down, right, and down-right diagonal.
Keep track of the minimum sum at each cell and update it based on the minimum of the three possible moves.
Finally, the minimum sum at the top left corner will be the answer.
Q43. When you search for a particular product in amazon, it displays some of the search results. But, only few particular products which are available in amazon are displayed, not all. How does this happen? I told M...
read moreAmazon displays only a subset of search results based on various factors like relevance, popularity, and user preferences.
Amazon uses algorithms to determine which products to display in search results.
Factors considered include product relevance, customer reviews, sales rank, and availability.
Machine learning techniques may be used to personalize search results based on user behavior and preferences.
Amazon also considers factors like seller reputation and fulfillment options...read more
Q44. There exists a 3x3 matrix, start from the first element reach the last element of the matrix, between each edges there exists a weight. Reach the destination such that the sum of weights should be small. It was...
read moreThe question is about finding the shortest path in a 3x3 matrix with weighted edges.
This is a graph traversal problem.
Use a graph algorithm like Dijkstra's algorithm or A* search to find the shortest path.
Assign weights to the edges and calculate the sum of weights for each possible path.
Choose the path with the smallest sum of weights as the shortest path.
Q45. Vertical Order Traversal Problem Statement
You are given a binary tree, and the task is to perform a vertical order traversal of the values of the nodes in the tree.
For a node at position ('X', 'Y'), the posit...read more
Perform vertical order traversal of a binary tree based on decreasing 'Y' coordinates.
Traverse the binary tree level by level and maintain the position of each node
Use a map to store nodes at each position and sort them based on 'Y' coordinates
Print the nodes in sorted order for each position to get the vertical order traversal
Q46. Find K Closest Elements
Given a sorted array 'A' of length 'N', and two integers 'K' and 'X', your task is to find 'K' integers from the array closest to 'X'. If two integers are at the same distance, prefer th...read more
Given a sorted array, find K integers closest to X, preferring smaller ones in case of same distance.
Use binary search to find the closest element to X in the array.
Maintain two pointers to expand around the closest element to find K closest elements.
Compare distances and values to select the K closest elements, preferring smaller ones if distances are equal.
Q47. Subset Sum Equal To K Problem Statement
Given an array/list of positive integers and an integer K, determine if there exists a subset whose sum equals K.
Provide true
if such a subset exists, otherwise return f...read more
Given an array of positive integers and an integer K, determine if there exists a subset whose sum equals K.
Use dynamic programming to solve this problem efficiently
Create a 2D array to store if a subset with a particular sum exists
Iterate through the array and update the 2D array accordingly
Check if the value at the end of the iteration is true for the given K
Q48. Remove Duplicates from String Problem Statement
You are provided a string STR
of length N
, consisting solely of lowercase English letters.
Your task is to remove all duplicate occurrences of characters in the s...read more
Remove duplicate occurrences of characters in a given string.
Use a hash set to keep track of characters seen so far.
Iterate through the string and add non-duplicate characters to a new string.
Return the new string without duplicate characters.
Q49. Valid Parentheses Problem Statement
Given a string 'STR' consisting solely of the characters “{”, “}”, “(”, “)”, “[” and “]”, determine if the parentheses are balanced.
Input:
The first line contains an integer...read more
Check if given strings with parentheses are balanced or not.
Use a stack to keep track of opening parentheses
Iterate through the string and push opening parentheses onto the stack
When a closing parenthesis is encountered, pop from the stack and check if it matches the closing parenthesis
If stack is empty at the end and all parentheses are matched, the string is balanced
Q50. Delete a Node from a Linked List
You are provided with a linked list of integers. Your task is to implement a function that deletes a node located at a specified position 'POS'.
Input:
The first line contains a...read more
Implement a function to delete a node from a linked list at a specified position.
Traverse the linked list to find the node at the specified position.
Update the pointers of the previous and next nodes to skip the node to be deleted.
Handle edge cases such as deleting the head or tail of the linked list.
Ensure to free the memory of the deleted node to avoid memory leaks.
To maximize the number of balloons burst with an arrow, target the balloons with the most adjacent balloons.
Identify clusters of balloons that are adjacent to each other.
Target the balloons in the clusters with the most adjacent balloons to burst the maximum number.
Consider the position and size of the clusters to strategically burst the balloons.
Q52. BFS Traversal in a Graph
Given an undirected and disconnected graph G(V, E) where V vertices are numbered from 0 to V-1, and E represents edges, your task is to output the BFS traversal starting from the 0th ve...read more
BFS traversal in a disconnected graph starting from vertex 0.
Implement BFS algorithm to traverse the graph starting from vertex 0.
Use a queue to keep track of visited nodes and their neighbors.
Ensure to print the traversal sequence in the correct order.
Handle disconnected components by checking for unvisited nodes.
Follow the BFS approach of exploring neighbors before moving to the next level.
Q53. Replace Spaces in a String
Given a string STR
consisting of words separated by spaces, your task is to replace all spaces between words with the characters "@40".
Input:
The first line contains an integer ‘T’ d...read more
Replace spaces in a string with '@40'.
Iterate through each character in the string
Replace spaces with '@40'
Return the modified string
Q54. Similar String Groups Problem Statement
Two strings S1
and S2
are considered similar if either S1
equals S2
or we can swap two letters of S1
at different positions so that it equals S2
.
Input:
The first line of...read more
The problem involves determining the number of similar string groups in a given list of strings based on a specific criteria.
Iterate through each pair of strings in the list and check if they are similar based on the given criteria.
Use a hash set to keep track of visited strings to avoid counting duplicates in the same group.
Consider implementing a function to check if two strings are similar by allowing at most one swap of characters.
Count the number of distinct groups of si...read more
Q55. Character Counting Challenge
Create a program that counts and prints the total number of specific character types from user input. Specifically, you need to count lowercase English alphabets, numeric digits (0-...read more
Create a program to count lowercase alphabets, digits, and white spaces from user input until '$' is encountered.
Read characters from input stream until '$' is encountered
Count lowercase alphabets, digits, and white spaces separately
Print the counts of each character type as three integers separated by spaces
Q56. Dijkstra's Shortest Path Problem
Given an undirected graph with ‘V’ vertices (labeled 0, 1, ... , V-1) and ‘E’ edges, where each edge has a weight representing the distance between two connected nodes (X, Y).
Y...read more
Dijkstra's algorithm is used to find the shortest path from a source node to all other nodes in a graph with weighted edges.
Implement Dijkstra's algorithm to find the shortest path distances from the source node to all other nodes.
Use a priority queue to efficiently select the next node with the shortest distance.
Update the distances of neighboring nodes based on the current node's distance and edge weights.
Handle disconnected vertices by assigning a large value (e.g., 214748...read more
Q57. How would I explain the concept of prime number to an illiterate?
A prime number is a number that is divisible only by 1 and itself.
A prime number has exactly two factors: 1 and itself.
Prime numbers cannot be divided evenly by any other number.
Examples of prime numbers include 2, 3, 5, 7, 11, 13, 17, etc.
Q58. What will be the key and what will be the values? The product will be the key. The brands will be the values.
The product will be the key and the brands will be the values.
The key in this case refers to the unique identifier for each product.
The values are the different brands associated with each product.
For example, if the product is a smartphone, the key could be the model number and the values could be the different brands that manufacture that model.
Q59. What js E cheque ? And what is the time for its clearance
An e-cheque is an electronic version of a paper cheque that is used for making payments online.
E-cheques are created and signed digitally, eliminating the need for physical paper.
They are typically used for online transactions and can be deposited into a bank account electronically.
The clearance time for e-cheques varies depending on the bank and the specific transaction.
It can take anywhere from a few hours to several business days for an e-cheque to clear.
During the clearan...read more
Approach to low-level system design involves understanding requirements, breaking down components, defining interfaces, and optimizing performance.
Understand the requirements and constraints of the system
Break down the system into smaller components/modules
Define clear interfaces between components for communication
Optimize performance by considering data structures, algorithms, and resource utilization
Q61. Five advantages of spring boot Which java version you currently use? Features of the java version you use Output from the code Difference between this and super In order to update the string, which will be bett...
read moreSpring Boot offers advantages like rapid development, easy configuration, embedded servers, production-ready features, and more.
Rapid development: Spring Boot simplifies the setup and configuration of Spring applications, allowing developers to focus on writing business logic.
Easy configuration: Spring Boot provides auto-configuration, reducing the need for manual setup and boilerplate code.
Embedded servers: Spring Boot comes with embedded servers like Tomcat, Jetty, and Unde...read more
Q62. Do you know Radix Sort? Where it is used? Radix sort can be applied in amazon.
Radix sort is a sorting algorithm that sorts integers by processing individual digits from least significant to most significant.
Radix sort is a non-comparative sorting algorithm.
It sorts numbers by grouping them based on each digit's value.
It is commonly used for sorting strings in lexicographic order.
Radix sort has linear time complexity, making it efficient for large datasets.
Q63. Suggest as many methods as possible for finding the nth largest element in an unsorted linked list
Methods to find nth largest element in an unsorted linked list
Traverse the linked list and store elements in an array, sort the array and return the nth largest element
Use quickselect algorithm to find the nth largest element in O(n) time complexity
Implement a max heap and extract the nth largest element
Divide the linked list into smaller sublists and recursively find the nth largest element
Use merge sort to sort the linked list and return the nth largest element
Hashing is a process of converting input data into a fixed-size string of bytes using a hash function.
Hashing is used to securely store passwords by converting them into a hash value before storing in a database.
Hashing is used in data structures like hash tables to quickly retrieve data based on a key.
Common hash functions include MD5, SHA-1, and SHA-256.
Hashing can be implemented in programming languages like Python using libraries like hashlib.
Q65. What data structure do they use? Hash tables.
Hash tables are a data structure that uses a hash function to map keys to values, providing efficient lookup, insertion, and deletion.
Hash tables use a hash function to convert keys into array indices.
They provide constant-time average case complexity for search, insert, and delete operations.
Collisions can occur when different keys map to the same index, which can be resolved using techniques like chaining or open addressing.
Examples of hash table implementations include Pyt...read more
To check internet connection on a system, you can use various methods like pinging a website or checking network status.
Use ping command to check connectivity to a website (e.g. ping www.google.com)
Check network status using network settings or command line tools
Try accessing a website or online service to verify internet connection
The Fibonacci series has applications in various fields such as mathematics, computer science, art, and nature.
Used in algorithms for optimization problems and dynamic programming.
Found in nature, such as the arrangement of leaves on a stem, the branching of trees, and the spiral shapes of shells.
Applied in financial markets for predicting stock prices and analyzing market trends.
Utilized in art and design for creating visually appealing patterns and compositions.
Q68. what is hashing and how will you implement?
Hashing is a process of converting data into a fixed-size numerical value called a hash code.
Hashing is used to quickly retrieve data from large datasets.
It is commonly used in data structures like hash tables and hash maps.
Hash functions should be fast, deterministic, and produce unique hash codes for different inputs.
Examples of hash functions include MD5, SHA-1, and SHA-256.
You can find a defective ball among 10 given balls in 2 attempts using a two-pan balance scale.
Divide the 10 balls into two groups of 5 each.
Weigh the two groups on the balance scale.
If one group is heavier, it contains the defective ball. If they are equal, the defective ball is in the remaining 5 balls.
Divide the group of 5 balls with the defective one into two groups of 2 and 3 balls.
Weigh the two groups on the balance scale.
If one group is heavier, it contains the defecti...read more
Q70. Application of Fibonacci series in day-to-day life.
The Fibonacci series can be applied in day-to-day life for various purposes.
Financial planning: Fibonacci numbers can be used to calculate investment growth and determine optimal investment strategies.
Architecture and design: Fibonacci ratios can be used to create aesthetically pleasing designs and layouts.
Nature and biology: Fibonacci patterns can be observed in the growth of plants, arrangement of leaves, and formation of shells.
Music and art: Fibonacci sequences can be use...read more
I remain calm, assess the situation, prioritize tasks, communicate effectively, and collaborate with team members to find a solution.
Remain calm and composed under pressure
Assess the situation to understand the root cause
Prioritize tasks based on urgency and impact
Communicate effectively with team members and stakeholders
Collaborate with team members to brainstorm and implement solutions
Rate limiter can be designed using token bucket algorithm to control the rate of requests.
Use token bucket algorithm to control the rate of requests
Set a limit on the number of requests allowed within a certain time frame
Track the number of requests made and refill the bucket at a constant rate
Reject requests that exceed the limit
Q73. Explain the concepts of Object Oriented Programming
Object Oriented Programming is a programming paradigm that uses objects to represent real-world entities.
Encapsulation: bundling data and methods that operate on that data within one unit
Inheritance: creating new classes from existing ones, inheriting their properties and methods
Polymorphism: ability of objects to take on multiple forms or behaviors
Abstraction: hiding complex implementation details and providing a simplified interface
Example: A car object can have properties ...read more
Q74. Design classes for educational institutions in a city
Design classes for educational institutions in a city
Identify the main entities: schools, students, teachers, courses
Create a School class with attributes like name, address, and a list of students and teachers
Create a Student class with attributes like name, age, and a list of courses
Create a Teacher class with attributes like name, specialization, and a list of courses
Create a Course class with attributes like name, duration, and a list of students and teachers
Establish rel...read more
Stack is used for static memory allocation and stores local variables, while Heap is used for dynamic memory allocation and stores objects.
Stack is faster than Heap as it has a fixed size and memory allocation is done at compile time.
Heap is slower than Stack as memory allocation is done at runtime and requires more complex management.
Stack memory is limited and typically smaller in size, while Heap memory is larger and can grow as needed.
Objects in OOP are typically stored i...read more
To measure exactly 15 minutes using two hourglasses of 7 and 11 minutes, start both hourglasses together and then flip the 7-minute hourglass when it runs out.
Start both hourglasses at the same time.
When the 7-minute hourglass runs out, flip it immediately.
When the 11-minute hourglass runs out, 4 minutes will have passed on the 7-minute hourglass. This gives a total of 15 minutes.
Q77. Can you describe the system design for the checkout feature on Amazon, including the request body, API calls, load balancing, database caching, and content delivery network (CDN) considerations?
The system design for the checkout feature on Amazon involves request body, API calls, load balancing, database caching, and CDN considerations.
Request body includes user's selected items, shipping address, payment details, etc.
API calls are made to process payment, update inventory, and send confirmation emails.
Load balancing ensures even distribution of traffic across multiple servers to handle checkout requests efficiently.
Database caching helps in storing frequently acces...read more
When you type a URL in a web browser, the browser sends a request to the server hosting the website, which then responds with the necessary files to display the webpage.
Browser checks cache for DNS resolution
If not found, browser sends a DNS query to resolve the domain name to an IP address
Browser establishes a TCP connection with the server
Browser sends an HTTP request to the server for the webpage
Server processes the request and sends back the necessary files (HTML, CSS, JS...read more
Q79. no of pairs between 1 and N satisfy relation pow(a,3)+pow(b,3)=pow(c,3)+pow(d,3).a,b,c,d<=N
The question asks for the number of pairs between 1 and N that satisfy a specific mathematical relation.
The relation is pow(a,3) + pow(b,3) = pow(c,3) + pow(d,3)
The values of a, b, c, and d should be less than or equal to N
Count the number of pairs that satisfy the relation
Q80. find the and return if the given file path existing in the given file hierarcy(file system).
Check if a given file path exists in the file system hierarchy and return the result.
Use file system APIs to check if the given file path exists in the hierarchy.
Traverse the file system hierarchy starting from the root directory to find the given file path.
Return true if the file path exists, false otherwise.
Q81. Show the abstraction and write code for function overriding
Abstraction is hiding the implementation details, function overriding is providing a new implementation for a method in a subclass.
Abstraction involves hiding the complex implementation details and showing only the necessary features to the user.
Function overriding occurs in inheritance when a subclass provides a specific implementation for a method that is already defined in its superclass.
Example: Parent class 'Animal' has a method 'makeSound()', subclass 'Dog' overrides th...read more
Q82. Give a few test cases for a bank transaction
Test cases for a bank transaction
Transaction amount within account balance limit
Transaction amount exceeds account balance limit
Transaction to a valid account number
Transaction to an invalid account number
Transaction with correct transaction code
Transaction with incorrect transaction code
Transaction during bank working hours
Transaction outside bank working hours
Q83. Given an array of numbers find the subset of numbers that give zero sum.
Find subset of numbers in array that sum up to zero.
Use a nested loop to iterate through all possible subsets.
Calculate the sum of each subset and check if it equals zero.
Store the subset if the sum is zero.
Optimize the solution by using a hash set to store the cumulative sum of elements.
OOP is a programming paradigm based on the concept of objects, which can contain data in the form of fields and code in the form of procedures.
OOP focuses on creating objects that interact with each other to solve problems.
Key concepts include encapsulation, inheritance, and polymorphism.
Encapsulation involves bundling data and methods that operate on the data into a single unit.
Inheritance allows classes to inherit attributes and methods from other classes.
Polymorphism enabl...read more
Q85. Optimal path cost and path in a matrix . Dynamic programming
Finding optimal path cost and path in a matrix using dynamic programming.
Dynamic programming is a technique to solve problems by breaking them down into smaller subproblems and solving them recursively.
In this case, we can use dynamic programming to find the optimal path cost and path in a matrix.
We can start by defining a 2D array to store the minimum cost of reaching each cell in the matrix.
Then, we can use a recursive function to calculate the minimum cost of reaching the ...read more
Q86. What you do if the customer is not happy for genivan cause?
Listen to their concerns, apologize, offer a solution, and follow up to ensure satisfaction.
Listen actively to their concerns and empathize with their situation.
Apologize for any inconvenience caused and take responsibility for the issue.
Offer a solution that addresses their concerns and meets their needs.
Follow up with the customer to ensure their satisfaction and address any further concerns.
Document the issue and the steps taken to resolve it for future reference.
Q87. Common puzzle- There are three boxes,one box of blue balls, one green and one mixed ,all labelled incorrectly. In how many trials will i label them correctly...
read moreThe boxes are labelled incorrectly with blue, green, and mixed balls. How many trials are needed to correctly label them?
Start by picking a ball from the box labelled 'mixed'. Since all labels are incorrect, this ball must be either blue or green.
Now, you can correctly label the box with the remaining two labels based on the color of the ball picked from the 'mixed' box.
This can be done in just one trial by picking a ball from the 'mixed' box.
Q88. A recursive program to print numbers in ascending order
A recursive program to print numbers in ascending order
Use a recursive function that takes a starting number and an ending number as parameters
Print the starting number and recursively call the function with starting number + 1 and the same ending number
Base case: stop recursion when starting number is greater than ending number
Q89. Program to implement Dijkstra’s algorithm
Dijkstra's algorithm finds the shortest path between nodes in a graph.
Create a graph with nodes and edges
Assign a tentative distance to each node
Set the initial node as current and mark it visited
For each neighbor of the current node, calculate the tentative distance
If the tentative distance is less than the current distance, update the distance
Mark the current node as visited and select the unvisited node with the smallest tentative distance
Repeat until the destination node ...read more
Q90. Running time of Radix sort? O(nk)
Radix sort has a running time of O(nk), where n is the number of elements and k is the length of the longest element.
Radix sort is a non-comparative sorting algorithm that sorts elements by their individual digits or characters.
It works by distributing the elements into 10 buckets based on the value of the least significant digit, then repeatedly redistributing them based on the next significant digit.
The process continues until all digits have been considered, resulting in a...read more
Q91. There are 10 weights of which two weigh less than the others. Using a balance how will i identify the defective ones...
read moreQuery to find the nth highest salary from a database
Use the ORDER BY clause to sort salaries in descending order
Use the LIMIT clause to select the nth highest salary
Consider handling cases where there may be ties for the nth highest salary
Q93. How many A4 sheets are sold in India per day?
It is impossible to accurately determine the number of A4 sheets sold in India per day.
There is no centralized data on the sales of A4 sheets in India.
The number of A4 sheets sold can vary greatly depending on the region and industry.
Factors such as digitalization and environmental concerns may also impact sales.
Estimates or projections may be available from specific companies or industries.
Market research firms may have data on the overall paper market in India.
malloc is a function in C for dynamic memory allocation, while new is an operator in C++ for dynamic memory allocation and object creation.
malloc is a function in C, while new is an operator in C++.
malloc returns a void pointer, while new returns a pointer to the type being allocated.
malloc does not call constructors, while new calls constructors for object initialization.
malloc requires manual memory deallocation with free, while new automatically calls the destructor and de...read more
Q95. Program to reverse a singly linked list
A program to reverse a singly linked list
Create a new empty linked list
Traverse the original linked list and insert each node at the beginning of the new list
Return the new list
Q96. how to find cycle in graph
To find a cycle in a graph, use depth-first search (DFS) and keep track of visited nodes.
Implement DFS algorithm to traverse the graph
Maintain a visited array to keep track of visited nodes
If a visited node is encountered again during DFS, a cycle exists
Q97. Give examples of abstraction and polymorphism
Abstraction is hiding implementation details while polymorphism is using a single interface for multiple types.
Abstraction: Encapsulation, Interfaces, Abstract classes
Polymorphism: Method Overloading, Method Overriding, Interfaces
Abstraction Example: Car - we don't need to know how the engine works to drive it
Polymorphism Example: Animal - different animals have different sounds but they all have a 'makeSound' method
Q98. What is shortest path problem ,and write a code for it
Shortest path problem is finding the shortest path between two nodes in a graph.
It is a common problem in graph theory and computer science.
Dijkstra's algorithm and Bellman-Ford algorithm are commonly used to solve it.
The problem can be solved using dynamic programming and graph traversal techniques.
Examples include finding the shortest route between two cities on a map or the shortest path for a robot to navigate a maze.
C is a procedural programming language while C++ is an object-oriented programming language with features like classes and inheritance.
C is a procedural programming language, while C++ is a multi-paradigm language with support for object-oriented programming.
C does not support classes and objects, while C++ does.
C does not have features like inheritance and polymorphism, which are present in C++.
C is a subset of C++, meaning that C++ includes all of C's features and adds new ...read more
Q100. How will you track payment failure count and make it fail safe
Track payment failure count and ensure fail safe measures
Implement a system to track payment failure count in real-time
Set up alerts for payment failures exceeding a certain threshold
Automate retries for failed payments with back-off strategies
Implement logging and monitoring to track payment failure trends
Integrate with payment gateway APIs to handle failures gracefully
Top HR Questions asked in Diversitech General Engineering
Interview Process at Diversitech General Engineering
Top Interview Questions from Similar Companies
Reviews
Interviews
Salaries
Users/Month