Algorithms
Top 250 Algorithms Interview Questions and Answers 2024
250 questions found
Updated 8 Dec 2024
Q1. One question of sorting for a list of people belonging to different cities and states.
Sort a list of people by their cities and states.
Use a sorting algorithm like quicksort or mergesort.
Create a custom comparator function that compares the city and state of each person.
If two people belong to the same city and state, sort them by their names.
Example: [{name: 'John', city: 'New York', state: 'NY'}, {name: 'Jane', city: 'Boston', state: 'MA'}]
Example output: [{name: 'Jane', city: 'Boston', state: 'MA'}, {name: 'John', city: 'New York', state: 'NY'}]
Q2. A ball is left from a height of 10 meters. After bouncing first time it looses 10% of its previous height the next time it bounces. Write a code to calculate the number of bounces the ball goes through until it...
read moreCode to calculate number of bounces a ball goes through until it comes to rest.
Use a loop to simulate the bounces until the ball stops bouncing
Calculate the height of each bounce using the given formula
Keep track of the number of bounces in a counter variable
Q3. Coding Question - Find 2nd largest element in array with least time complexity
Find the 2nd largest element in an array with the least time complexity.
Sort the array in descending order and return the element at index 1.
Initialize two variables to keep track of the largest and second largest elements.
Iterate through the array and update the variables accordingly.
Return the second largest element.
Q4. Write a program to count vowels and consonants in string
A program to count the number of vowels and consonants in a given string.
Iterate through each character in the string
Check if the character is a vowel or consonant
Increment the respective count
Return the counts of vowels and consonants
Q5. Write a program to check if a string is a palindrome or not.
A program to check if a string is a palindrome or not.
A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward.
To check if a string is a palindrome, we can compare the characters from the beginning and end of the string.
If the characters match for all positions, the string is a palindrome.
We can ignore spaces, punctuation, and case sensitivity when checking for palindromes.
Q6. Search an element in sorted rotated array.
Search an element in sorted rotated array.
Use binary search to find the pivot point where the array is rotated.
Divide the array into two subarrays and perform binary search on the appropriate subarray.
Handle the cases where the target element is at the pivot point or not present in the array.
Q7. Find out positions of numbers form an array whose sum is 9.
The positions of numbers in an array whose sum is 9 need to be found.
Iterate through the array and check for pairs of numbers that add up to 9.
Store the positions of the numbers that satisfy the condition.
Return the positions as the result.
Q8. To find if a number is Prime or not and optimise your written code.
Check if a number is prime and optimize the code.
Start by checking if the number is less than 2, in which case it is not prime.
Iterate from 2 to the square root of the number and check if any of them divide the number evenly.
If a divisor is found, the number is not prime. Otherwise, it is prime.
Algorithms Jobs
Q9. Find max square area in a binary matrix
Find the maximum area of a square in a binary matrix.
Iterate through the matrix and for each cell, calculate the maximum square area that can be formed with that cell as the top-left corner.
Use dynamic programming to store the maximum square area at each cell.
Keep track of the maximum area encountered so far and return it as the result.
Q10. find the count of alphabets in a sentance
To find the count of alphabets in a sentence, we can iterate through each character and count the alphabets.
Iterate through each character in the sentence
Check if the character is an alphabet using regex or ASCII values
If the character is an alphabet, increment the count
Return the count
Q11. Write the code for Fibonacci series up to 10
Code for Fibonacci series up to 10
Declare two variables to store the first two numbers of the series
Use a loop to generate the next numbers in the series by adding the previous two
Print the series up to 10
Q12. Difference between Merge sort and Heap sort?
Merge sort and Heap sort are both comparison-based sorting algorithms, but they differ in their approach and performance.
Merge sort is a divide-and-conquer algorithm that divides the input array into two halves, recursively sorts them, and then merges the sorted halves.
Heap sort is based on the concept of a binary heap, which is a complete binary tree where each node is greater than or equal to its children. It involves building a max heap and repeatedly extracting the maximu...read more
Q13. Write the algorithm for reversing the string
The algorithm reverses a given string.
Iterate through the string from the last character to the first character.
Append each character to a new string or an array in reverse order.
Return the reversed string or array.
Q14. Write the code to find factorial using function recursion.
Code to find factorial using function recursion
Define a function that takes an integer as input
Check if the input is 0 or 1, return 1 in that case
Otherwise, call the function recursively with input-1 and multiply it with the input
You are given two sorted arrays/list ‘arr1’ and ‘arr2’ and an integer k. You create a new sorted array by merging all the elements from ‘arr1’ and ‘arr2’. Your task is to find the ...read more
The task is to find the kth smallest element of a merged array created by merging two sorted arrays.
Merge the two sorted arrays into a single sorted array
Return the kth element of the merged array
Q16. Given a complex diagram, find out maximum frequency of operation
To determine maximum frequency of operation from a complex diagram
Identify the critical path in the diagram
Calculate the propagation delay of each component in the path
Use the formula fmax = 1 / (2 * propagation delay) to determine maximum frequency
Consider any setup or hold time requirements for flip-flops or other components
Ensure that the frequency is within the specifications of the components used
Q17. Explain logic of quick sort
Quick sort is a divide and conquer algorithm that sorts an array by partitioning it into two sub-arrays.
Choose a pivot element from the array
Partition the array around the pivot element
Recursively apply the above steps to the sub-arrays
Combine the sorted sub-arrays to get the final sorted array
Q18. How do you optimize the listing of Restaurants on Swiggy?
Optimizing the listing of Restaurants on Swiggy involves using data-driven strategies to improve visibility, relevance, and user experience.
Analyze user behavior and preferences to understand their needs and preferences
Implement a ranking algorithm based on factors like ratings, reviews, popularity, and delivery time
Optimize search functionality to ensure accurate and relevant results
Collaborate with restaurants to improve their online presence and menu offerings
Leverage cust...read more
Q19. For Example: N Cards are placed, if you flip a card, the next card will get reversed. If we move left to right, how much time will it take to get all cards reversed- question based on time complexity?
To reverse N cards, time complexity is O(N).
The time complexity to reverse N cards is O(N).
The algorithm needs to flip each card once, so the time complexity is linear.
The time it takes to reverse all cards is directly proportional to the number of cards.
For example, if there are 10 cards, it will take 10 flips to reverse all of them.
Q20. Write a code to find if two words are anagrams
Code to check if two words are anagrams
Convert both words to lowercase
Remove all spaces and punctuation
Sort the characters in both words
Compare the sorted words
Q21. What are the types of ML algorithms? Give an example of each.
There are several types of ML algorithms, including supervised learning, unsupervised learning, and reinforcement learning.
Supervised learning: algorithms learn from labeled data to make predictions or classifications (e.g., linear regression, decision trees)
Unsupervised learning: algorithms find patterns or relationships in unlabeled data (e.g., clustering, dimensionality reduction)
Reinforcement learning: algorithms learn through trial and error by interacting with an enviro...read more
Q22. Write a fibanocci or simple coding question
Write a function to calculate the nth Fibonacci number.
Create a function that takes an integer n as input
If n is 0 or 1, return n
Otherwise, return the sum of the previous two Fibonacci numbers
Use recursion to call the function with n-1 and n-2 as inputs
Q23. Fill up numbers from 1-25 in a 5X5 matrix such that each number is average of the adjacent numbers
Fill a 5X5 matrix with numbers 1-25 such that each number is average of adjacent numbers.
Start with the center number and fill the adjacent numbers with consecutive odd numbers
Fill the remaining numbers in a spiral pattern, using the average of adjacent numbers
Check for edge cases and adjust the numbers accordingly
Example: 13 12 11 10 9, 14 3 2 1 8, 15 4 center 6 7, 16 5 18 19 20, 17 22 23 24 25
Q24. 3. Check if two strings are anagram
Check if two strings are anagram
Sort both strings and compare them
Use a hash table to count the frequency of each character in both strings and compare the hash tables
Use an array of size 26 to count the frequency of each letter in both strings and compare the arrays
Q25. The number of swapping operations required to sort the array [8,22,7,9,31,19,5,13] in bubblesort?
The number of swaps required to sort an array using bubblesort
Bubble sort compares adjacent elements and swaps them if they are in the wrong order
Count the number of swaps required to sort the given array
The given array requires 19 swaps to be sorted using bubblesort
Q26. How RPN is calculated
RPN is calculated using a postfix notation where operators come after the operands.
RPN stands for Reverse Polish Notation
Operators come after the operands in RPN
RPN is evaluated using a stack data structure
Example: 3 4 + 5 * = 35
Example: 10 5 / 2 * = 4
Q27. Program to find the number of trailing zeros in a factorial
Program to find the number of trailing zeros in a factorial
Count the number of 5s in the factorial
Divide the number by 5 and add the quotient to the answer
Repeat until quotient is less than 5
Q28. Swap two number without using temperory variable
Swap two numbers without using a temporary variable.
Use addition and subtraction to swap the values
Use XOR operator to swap the values
Use multiplication and division to swap the values
Q29. What is the key of remove duplicates
The key to remove duplicates is to iterate through the array and keep track of unique elements.
Iterate through the array and compare each element with the rest of the elements.
If a duplicate is found, remove it from the array.
Keep track of unique elements using a hash set or dictionary.
Return the modified array with duplicates removed.
Q30. What is the difference between BFS and DFS
BFS and DFS are two popular graph traversal algorithms. BFS explores the graph level by level while DFS explores the graph depth by depth.
BFS uses a queue data structure while DFS uses a stack or recursion.
BFS is guaranteed to find the shortest path between two nodes while DFS may not.
BFS is better suited for finding the shortest path, while DFS is better suited for finding all possible paths or cycles.
BFS has a higher memory requirement than DFS.
Examples of BFS include findi...read more
Q31. implement bfs in graph
BFS (Breadth-First Search) is a graph traversal algorithm that explores all the vertices of a graph in breadth-first order.
Create a queue to store the visited vertices
Start with the initial vertex and enqueue it
While the queue is not empty, dequeue a vertex and mark it as visited
Enqueue all the adjacent vertices of the dequeued vertex that are not yet visited
Repeat until the queue is empty
Q32. Write algo to mirror a given Binary Tree?
Algorithm to mirror a given Binary Tree
Create a function to swap left and right child nodes of a given node
Recursively call the function on left and right child nodes
Base case: if node is null, return
Call the function on the root node of the binary tree
Q33. Find count of words in a sentence using Map
Count words in a sentence using Map
Split the sentence into an array of words
Create a Map object
Loop through the array and add each word as a key to the map with a value of 1
If the word already exists in the map, increment its value by 1
Return the map
Q34. explain all the serach algorithm you know with space and Time complexities
Explanation of search algorithms with their space and time complexities.
Linear Search - O(n) time complexity, O(1) space complexity
Binary Search - O(log n) time complexity, O(1) space complexity
Jump Search - O(√n) time complexity, O(1) space complexity
Interpolation Search - O(log log n) time complexity, O(1) space complexity
Exponential Search - O(log n) time complexity, O(1) space complexity
Fibonacci Search - O(log n) time complexity, O(1) space complexity
Q35. Find all permutations of a given string. (Not in lexicographic order)
Find all permutations of a given string.
Use recursion to swap each character with every other character in the string.
Repeat the process for each substring.
Add the permutation to an array.
Q36. Write code to find max length subarray matching the given sum
Code to find max length subarray matching the given sum
Use a sliding window approach to iterate through the array
Keep track of the current sum and the maximum length subarray
If the current sum exceeds the given sum, move the window's left pointer
If the current sum matches the given sum, update the maximum length subarray
Return the maximum length subarray
Q37. Q2. Write insertion sort algo.
Insertion sort is a simple sorting algorithm that builds the final sorted array one item at a time.
Start with the second element and compare it with the first element, swap if necessary
Move to the third element and compare it with the first and second elements, swap if necessary
Continue this process until the entire array is sorted
Time complexity is O(n^2)
Q38. Find longest increasing sequence in a matrix
Find longest increasing sequence in a matrix
Iterate through each element in the matrix
For each element, check its neighbors to find the longest increasing sequence
Keep track of the longest sequence found so far
Q39. How will you approach the problem of tracing all squares in a chess board by doing valid moves of a Knight, without repeating any squre?
Tracing all squares in a chess board by valid moves of a Knight without repeating any square.
Create a 2D array to represent the chess board.
Start from any square and mark it as visited.
Generate all possible moves of a Knight from the current square.
Check if the move is valid and not visited before.
If yes, mark the square as visited and add it to the path.
Repeat the above steps until all squares are visited.
If no more moves are possible, backtrack to the previous square and tr...read more
Q40. What memoization techniques are you familiar with?
Memoization techniques involve storing the results of expensive function calls and returning the cached result when the same inputs occur again.
Using a hash table to store previously computed results
Implementing memoization with dynamic programming
Memoizing recursive functions to avoid redundant calculations
Q41. What is the best approach to find the missing number from set of consecutive n numbers
One approach is to calculate the sum of all numbers in the set and then subtract the sum of the given numbers to find the missing number.
Calculate the sum of all numbers in the set using the formula n*(n+1)/2, where n is the total number of elements in the set.
Calculate the sum of the given numbers in the set.
Subtract the sum of the given numbers from the sum of all numbers to find the missing number.
Q42. Write program to find even and odd number using lambda expression
Program to find even and odd number using lambda expression
Create a list of numbers
Use lambda expression to filter even and odd numbers
Print the even and odd numbers
Q43. a program to print random token numbers?
A program to print random token numbers.
Generate random numbers using a random number generator
Convert the numbers to strings and store them in an array
Print the token numbers from the array
Q44. Get 2 nd max element from array
Get 2nd max element from array of strings
Sort the array in descending order
Return the element at index 1
Handle edge cases like array length < 2
Q45. What is Min-Cut placement algorithm? Given some block sizes, use the algorithm to place them on a given chip area
Min-Cut placement algorithm is used to place blocks on a given chip area.
Min-Cut algorithm partitions the chip into two parts and minimizes the cut between them
It is a graph-based algorithm that uses a flow network to represent the chip and its blocks
The algorithm iteratively partitions the network until all blocks are placed
Example: Placing logic gates on a microprocessor chip
Q46. sort the elements of an unsorted array
Use any sorting algorithm to sort the elements of an unsorted array.
Choose an appropriate sorting algorithm based on the size of the array and the type of elements.
Common sorting algorithms include bubble sort, insertion sort, selection sort, merge sort, quick sort, and heap sort.
Implement the chosen algorithm in the programming language of your choice.
Test the sorting function with various input arrays to ensure correctness.
Q47. Find sub-matrix from a matrix of both positive and negative numbers with maximum sum.
Find sub-matrix with maximum sum from a matrix of positive and negative numbers.
Use Kadane's algorithm to find maximum sum subarray in each row.
Iterate over all possible pairs of rows and find the maximum sum submatrix.
Time complexity: O(n^3), where n is the number of rows or columns.
Q48. Build a pyramid pattern of numbers in O(n) time using any language.
Print a pyramid pattern of numbers in O(n) time.
Use nested loops to print the pattern.
The outer loop will iterate from 1 to n.
The inner loop will iterate from 1 to the current value of the outer loop.
Print the inner loop variable and a space after each iteration.
Print a new line after the inner loop completes.
Q49. Devise an algorithm to determine the Nth-to-Last element in a singly linked list of unknown length. If N = 0, then your algorithm must return the last element. You should parse the list only once
Algorithm to find Nth-to-Last element in a singly linked list of unknown length
Traverse the list and maintain two pointers, one at the beginning and one at Nth node from beginning
Move both pointers simultaneously until the second pointer reaches the end of the list
The first pointer will be pointing to the Nth-to-Last element
If N=0, return the last element
Parse the list only once
Q50. Find max sum of sub array
Find the maximum sum of a subarray within an array of integers.
Iterate through the array and keep track of the current sum and maximum sum seen so far.
If the current sum becomes negative, reset it to 0 as it won't contribute to the maximum sum.
Return the maximum sum found after iterating through the entire array.
Q51. Write optimized code of Prime Number(on paper)
Optimized code to find prime numbers
Start checking from 2 up to the square root of the number
Use the modulo operator to check if the number is divisible by any smaller number
If the number is divisible by any smaller number, it is not prime
If the number is not divisible by any smaller number, it is prime
Q52. What are the different types of complexities?
There are various types of complexities, such as time complexity, space complexity, algorithmic complexity, and computational complexity.
Time complexity refers to the amount of time taken by an algorithm to run, often measured in terms of the input size.
Space complexity refers to the amount of memory space required by an algorithm to run, also measured in terms of the input size.
Algorithmic complexity refers to the efficiency of an algorithm in terms of time and space require...read more
Q53. Given a map of coffee shops and a person on the map give the closest n coffee shops to him
Given a map of coffee shops and a person, find the closest n coffee shops to him.
Use the person's location and calculate the distance to each coffee shop on the map.
Sort the coffee shops by distance and return the closest n.
Consider using a data structure like a priority queue to efficiently find the closest coffee shops.
Q54. Count the frequency of elements in an array
Count frequency of elements in an array of strings
Create a dictionary to store element frequency
Loop through array and update dictionary
Return dictionary
You are given a Binary Tree ‘root’. The given Binary Tree may or may not be a Binary Search Tree(BST) itself. Your task is to find the maximum sum of node values of any subtree that is a Binary S...read more
The task is to find the maximum sum of node values of any subtree that is a Binary Search Tree(BST).
Traverse the binary tree in a bottom-up manner
For each node, check if it forms a BST and calculate the sum of its subtree
Keep track of the maximum sum encountered so far
Return the maximum sum
You have been given two integer arrays/list(ARR1 and ARR2) of size N and M, respectively. You need to print their intersection; An intersection for this problem can be defined when both the ar...read more
The task is to find the intersection of two integer arrays/lists.
Read the number of test cases
For each test case, read the size and elements of the first array/list
Read the size and elements of the second array/list
Find the intersection of the two arrays/lists
Print the intersection elements in the order they appear in the first array/list
Q57. Find a index value present an array
Finding the index value of a given element in an array of strings.
Iterate through the array and compare each element with the given value.
If a match is found, return the index of that element.
If no match is found, return -1.
Q58. Find median of two sorted arrays. O(logM + logN)
Find median of two sorted arrays in O(logM + logN) time complexity.
Use binary search to find the partition point in both arrays.
Calculate the left and right elements of the partition in both arrays.
If the left elements are smaller than the right elements, we have found the median.
If not, adjust the partition point accordingly and repeat the process.
If the total number of elements is odd, median is the max of left elements.
If the total number of elements is even, median is the...read more
Q59. Find duplicates in a string and count repeated letters
Find duplicates in a string and count repeated letters
Iterate through each character in the string
Use a hash map to store the count of each character
If a character is already present in the hash map, increment its count
After iterating through the string, filter the hash map to get the duplicate characters and their counts
Q60. What is logic of amstrong number say its coding logic
Armstrong number is a number whose sum of cubes of its digits is equal to the number itself.
Armstrong number is also known as Narcissistic number.
For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153.
The coding logic involves breaking down the number into its individual digits, cubing them, and then adding them up.
Finally, the sum is compared with the original number to determine if it is an Armstrong number or not.
Q61. Write a code to swap to number without third variable
Swapping two numbers without using a third variable
Use addition and subtraction to swap the values
Use XOR operator to swap the values
Use multiplication and division to swap the values
Q62. 1. What is efficiency
Efficiency is the ability to do something in a way that achieves maximum productivity with minimum wasted effort or expense.
Efficiency is a measure of how well a system or process performs.
It is often expressed as a percentage of the total input that is converted into useful output.
For example, a car's fuel efficiency is measured in miles per gallon (MPG).
Efficiency can be improved by optimizing processes, reducing waste, and increasing productivity.
Efficiency is important in...read more
Q63. How do you quickly count the number of set bits in a 32-bit integer in linear time (with respect to the number of set bits)?
Count set bits in a 32-bit integer in linear time
Use bit manipulation to count set bits
Divide the integer into 16-bit chunks and count set bits in each chunk
Use lookup tables to count set bits in each 8-bit chunk
Use parallel processing to count set bits in multiple integers simultaneously
Q64. Find the total no of the island in a 2d matrix. Working code was required.
Find the total no of islands in a 2D matrix.
Use DFS or BFS to traverse the matrix.
Mark visited cells to avoid repetition.
Count the number of islands found.
Q65. find if number i power of 2
Check if a number is a power of 2.
A number is a power of 2 if it is greater than 0 and has only one bit set to 1.
Use bitwise operations to check if the number is a power of 2.
For example, 4 (100 in binary) is a power of 2, while 6 (110 in binary) is not.
Q66. Find nearest index of character in string for each index.
Find the nearest index of a character in a string for each index.
Create an array of strings to store the results.
Loop through each character in the string.
For each character, loop through the rest of the string to find the nearest index of the same character.
Store the result in the array.
Q67. - Find all distinct elements in a list
To find distinct elements in a list
Create an empty set
Iterate through the list and add each element to the set
Return the set
Q68. Was asked to design an algorithm for the snake and ladders game.
Algorithm for Snake and Ladders game
Create a board with 100 squares
Assign snakes and ladders to specific squares
Roll a dice to move player's token on the board
Check if the new position is a snake or ladder
Repeat until a player reaches the final square
Q69. 9)how to avoid hash collision
To avoid hash collisions, use a good hash function, increase the size of the hash table, and handle collisions using techniques like chaining or open addressing.
Use a good hash function that distributes the keys evenly across the hash table.
Increase the size of the hash table to reduce the chances of collisions.
Handle collisions using techniques like chaining (using linked lists) or open addressing (probing).
Chaining example: Store multiple values with the same hash key in a ...read more
Q70. How to Remove duplicate element from an array
To remove duplicate elements from an array, we can use a Set or loop through the array and compare each element.
Create a new Set from the array to remove duplicates
Loop through the array and compare each element to a new array without duplicates
Use filter() method to create a new array without duplicates
Q71. 8) To write program to iterate an array using pointer
Program to iterate an array using pointer
Declare a pointer variable and initialize it to the base address of the array
Use a loop to iterate through the array using the pointer variable
Increment the pointer variable in each iteration to point to the next element
Stop the loop when the pointer variable reaches the end of the array
Q72. What are the different sorting technique?
Sorting techniques are algorithms used to arrange data in a specific order.
Bubble Sort
Selection Sort
Insertion Sort
Merge Sort
Quick Sort
Heap Sort
Radix Sort
Q73. An unsorted array has numbers. Find the duplicate numbers and return the array.
Find duplicate numbers in an unsorted array and return the array.
Iterate through the array and keep track of seen numbers using a hash table.
If a number is already in the hash table, it is a duplicate.
Add the duplicate number to a new array and return it.
You have been given a 9 X 9 2D matrix 'MATRIX' with some cells filled with digits(1 - 9), and some empty cells (denoted by 0).
You need to find whether there exists a way to fill all the empty cells...read more
The task is to determine if a given 9x9 matrix can be filled with digits 1-9 to form a valid Sudoku solution.
Iterate through each cell in the matrix.
For each empty cell, try filling it with a digit from 1-9 and check if it satisfies the Sudoku conditions.
Use helper functions to check if the digit is valid in the current row, column, and sub-matrix.
If a valid digit is found, recursively fill the next empty cell.
If all cells are filled and the Sudoku conditions are satisfied, r...read more
Q75. Remove duplicates without using inbuilt methods
Removing duplicates without using inbuilt methods in JavaScript
Create an empty array to store unique values
Loop through the original array
Check if the current element exists in the unique array
If not, push it to the unique array
Return the unique array
Q76. Given two sequences of length N, how to find the max window of matching patterns. The patterns can be mutated
To find max window of matching patterns between two sequences of length N with mutated patterns.
Create a sliding window of size N and traverse both sequences simultaneously.
Check for matching patterns in the window and keep track of the maximum window with matching patterns.
Use a hash table to keep track of mutated patterns.
If a pattern is mutated, update the hash table and check if it matches with the other sequence.
Repeat until the end of both sequences is reached.
Return th...read more
Q77. Find if a given directed graph is cyclic or not
To check if a directed graph is cyclic or not
Use Depth First Search (DFS) algorithm to traverse the graph
Maintain a visited set to keep track of visited nodes
Maintain a recursion stack to keep track of nodes in the current DFS traversal
If a node is visited and is already in the recursion stack, then the graph is cyclic
If DFS traversal completes without finding a cycle, then the graph is acyclic
Q78. draw a flow chart to find if a no is even or not
Flow chart to determine if a number is even or not.
Start the flow chart with the input number
Check if the number is divisible by 2
If yes, then it is even
If no, then it is odd
Q79. What is a Brute Force Algorithm?
A Brute Force Algorithm is a method of solving problems by trying every possible solution.
It involves trying every possible combination of inputs to find the correct output.
It is a simple but inefficient algorithm.
It is commonly used in cryptography to crack passwords.
Examples include the exhaustive search algorithm and the traveling salesman problem.
Q80. find pair which have a given sum in a given array
Finding pairs in an array with a given sum.
Iterate through the array and for each element, check if the difference between the given sum and the element exists in the array.
Use a hash table to store the elements of the array and their indices for faster lookup.
If there are multiple pairs with the same sum, return any one of them.
If no pair is found, return null or an empty array.
Q81. Write a program to reverse a n integer
Program to reverse an integer
Convert the integer to a string
Reverse the string
Convert the reversed string back to an integer
Q82. How will you rotate matrix by 90 degrees clockwise and anticlockwise?
To rotate a matrix by 90 degrees clockwise, transpose the matrix and then reverse each row. To rotate anticlockwise, reverse each row and then transpose.
Transpose the matrix by swapping elements at (i, j) with (j, i)
Reverse each row of the transposed matrix
To rotate anticlockwise, reverse each row of the original matrix and then transpose
Q83. What is GCD? Explain in details
GCD stands for Greatest Common Divisor. It is the largest positive integer that divides two or more numbers without leaving a remainder.
GCD is used to find the highest common factor between two or more numbers.
It is often used in mathematical calculations and algorithms.
GCD can be calculated using various methods like Euclidean algorithm or prime factorization.
Example: GCD of 12 and 18 is 6, as 6 is the largest number that divides both 12 and 18 without leaving a remainder.
Q84. rotate a array k times
Rotate an array of strings k times
Create a temporary array to store elements that will be rotated
Use modulo operator to handle cases where k is greater than array length
Update the original array with elements from the temporary array
Q85. Write a code to multiply two matrices of dimension M*N and N*K
Code to multiply two matrices of dimension M*N and N*K.
Create a result matrix of dimension M*K.
Iterate through each row of the first matrix.
For each row, iterate through each column of the second matrix.
For each element in the row of the first matrix, multiply it with the corresponding element in the column of the second matrix.
Sum up the products and store the result in the corresponding position of the result matrix.
Repeat the process for all rows and columns.
Return the res...read more
Q86. Which is the best and less time consuming way to calculate factorial of a number?
The best and less time consuming way to calculate factorial of a number is using iterative approach.
Iteratively multiply the number with all the numbers from 1 to the given number
Start with a result variable initialized to 1
Multiply the result with each number in the range
Return the final result
Q87. Print first duplicate value in a string.
Find the first duplicate value in an array of strings.
Create a hash table to store the frequency of each string.
Iterate through the array and check if the string already exists in the hash table.
If it does, return the string. If not, add it to the hash table.
If no duplicates are found, return null or an appropriate message.
Q88. What are Fto searches and how it help the client?
FTO searches are Freedom to Operate searches conducted to assess potential patent infringement risks before launching a new product or service.
FTO searches involve analyzing existing patents to determine if there are any potential infringement risks for a new product or service.
They help clients understand the competitive landscape and make informed decisions about launching their products or services.
FTO searches can also identify opportunities for licensing or acquisition o...read more
Q89. Explian meaning of analysis
Analysis is the process of examining data or information to draw conclusions or make decisions.
Analysis involves breaking down complex information into smaller parts.
It requires identifying patterns, relationships, and trends in the data.
The results of analysis can be used to make informed decisions or recommendations.
Examples of analysis include financial analysis, market analysis, and risk analysis.
Q90. validate if string containg "{" and "}" are balanced or not
Check if a string containing '{' and '}' is balanced
Use a stack to keep track of opening braces
Iterate through the string and push '{' onto the stack and pop when '}' is encountered
If stack is empty at the end, the string is balanced
Q91. Write a pseudo code to find the k'th largest element in a array
Pseudo code to find the k'th largest element in an array
Sort the array in descending order
Return the element at index k-1
There are ‘N’ people numbered from 0 to N - 1, standing in a queue. You are given two arrays ‘Height’ and ‘Infront‘ consisting of ‘N’ non-negative integers. ‘Height[i]’ gives the height o...read more
The task is to find the actual order of people in a queue based on their heights and the number of taller people in front of them.
Iterate through the given arrays and create a list of tuples containing the height and number of taller people for each person.
Sort the list of tuples in descending order of height and ascending order of the number of taller people.
Create an empty result list and insert each tuple into the result list at the index specified by the number of taller ...read more
Q93. How to calculate the square root of a number?? note: your compiler does not support math.h
To calculate square root without math.h, use Newton's method.
Choose a number to find the square root of
Make an initial guess for the square root
Use Newton's method to refine the guess
Repeat until desired accuracy is achieved
Newton's method: new_guess = (guess + (number/guess))/2
Q94. Write code for QuickSort
QuickSort is a sorting algorithm that uses divide and conquer approach.
Choose a pivot element from the array
Partition the array into two sub-arrays, one with elements less than the pivot and one with elements greater than the pivot
Recursively apply the above steps to the sub-arrays
Combine the sorted sub-arrays to get the final sorted array
Q95. When a sorted array is ‘Rotated’, its last element becomes the first element and the remaining elements shift to the right. Write a function which takes an input array and returns the no. of times an array has ...
read moreFunction to find the no. of times a sorted array has been rotated.
Find the index of the minimum element in the array using binary search.
The number of times the array has been rotated is equal to the index of the minimum element.
Handle the case where the array is not rotated (minimum element at index 0).
Q96. Write a program to print numbers 1 to 100 with out using integer at all
Program to print numbers 1 to 100 without using integers
Create an array of strings containing the numbers from 1 to 100
Use a loop to iterate through the array and print each element
Q97. What is route planning or optimization?
Route planning or optimization is the process of finding the most efficient route for a given set of destinations.
It involves analyzing various factors such as distance, traffic, and time constraints.
The goal is to minimize travel time, distance, and cost while maximizing efficiency.
Examples include optimizing delivery routes for a logistics company or planning a road trip with multiple stops.
Route planning software and algorithms are commonly used to automate the process and...read more
Q98. Find Peak Element and majority element
Peak and majority element finding algorithms
Peak element: binary search for element greater than both neighbors
Majority element: Boyer-Moore voting algorithm
Boyer-Moore: iterate through array, count occurrences of each element, return element with count > n/2
Q99. find tree node from leet code
Finding a tree node from LeetCode involves traversing a tree data structure to locate a specific node.
Use depth-first search (DFS) or breadth-first search (BFS) to traverse the tree and find the target node.
Implement a recursive function to search for the node in the tree structure.
Consider using a stack or queue data structure to keep track of nodes to visit next.
Check if the current node is the target node, if not, recursively search in the left and right subtrees.
Handle ed...read more
Q100. Tell me something about heap sort
Heap sort is a comparison-based sorting algorithm that uses a binary heap data structure.
It divides the input into a sorted and an unsorted region.
It repeatedly extracts the maximum element from the unsorted region and inserts it into the sorted region.
It has a worst-case time complexity of O(n log n).
Top Interview Questions for Related Skills
Interview Questions of Algorithms Related Designations
Interview experiences of popular companies
Reviews
Interviews
Salaries
Users/Month