Top 250 Algorithms Interview Questions and Answers

Updated 21 Jan 2025

Q1. One question of sorting for a list of people belonging to different cities and states.

Ans.

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'}]

View 56 more answers
Frequently asked in

Q2. Coding Question - Find 2nd largest element in array with least time complexity

Ans.

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.

View 1 answer

Q3. How to find longest last occurring word in a sentence with multiple whitespace

Ans.

Finding the longest last occurring word in a sentence with multiple whitespace.

  • Split the sentence into words using whitespace as delimiter

  • Reverse the list of words

  • Iterate through the list and find the first occurrence of each word

  • Calculate the length of each last occurring word

  • Return the longest last occurring word

Add your answer
Frequently asked in

Q4. How to find the palindrome among first N numbers? Code it.

Ans.

To find palindrome among first N numbers, iterate from 1 to N and check if the number is equal to its reverse.

  • Iterate from 1 to N

  • For each number, check if it is equal to its reverse

  • If yes, it is a palindrome

Add your answer
Are these interview questions helpful?

Q5. Search an element in sorted rotated array.

Ans.

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.

View 2 more answers

Q6. Find out positions of numbers form an array whose sum is 9.

Ans.

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.

View 2 more answers
Share interview questions and help millions of jobseekers 🌟

Q7. Missing Number in Concatenated Sequence

You were given a sequence of consecutive nonnegative integers but missed one while appending them to create a string S. Your task is to identify the missing integer from ...read more

Ans.

The task is to find the missing number in a string of consecutive nonnegative integers.

  • Iterate through the string and check if each substring can form a valid number

  • If a substring forms a valid number, check if it is consecutive with the previous number

  • If a substring does not form a valid number or is not consecutive, it is the missing number

  • Handle edge cases such as multiple missing numbers or all numbers already present

Add your answer

Q8. Find max square area in a binary matrix

Ans.

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.

View 1 answer

Algorithms Jobs

Software Developer 3-8 years
IBM India Pvt. Limited
4.0
Bangalore / Bengaluru
Data Engineer 5-7 years
IBM India Pvt. Limited
4.0
Bangalore / Bengaluru
Software Developer 3-8 years
IBM India Pvt. Limited
4.0
Bangalore / Bengaluru

Q9. Difference between Merge sort and Heap sort?

Ans.

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

Add your answer
Frequently asked in

Q10. K-th Element of Two Sorted Arrays

You are provided with two sorted arrays, arr1 and arr2, along with an integer k. By merging all elements from arr1 and arr2 into a new sorted array, your task is to identify th...read more

Ans.

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

Add your answer

Q11. Write the code for Fibonacci series up to 10

Ans.

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

Add your answer

Q12. Given a complex diagram, find out maximum frequency of operation

Ans.

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

Add your answer
Frequently asked in

Q13. To find if a number is Prime or not and optimise your written code.

Ans.

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.

View 2 more answers

Q14. Program to print the elements of a matrix in spiral order recursively

Ans.

Program to print matrix elements in spiral order recursively

  • Create a recursive function to print the elements in spiral order

  • Define the boundaries of the matrix and traverse the matrix in spiral order

  • Call the recursive function to print the elements in spiral order

  • Handle edge cases such as empty matrix or matrix with only one row/column

Add your answer

Q15. How do you optimize the listing of Restaurants on Swiggy?

Ans.

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

View 2 more answers
Frequently asked in

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

Ans.

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.

Add your answer

Q17. What are the types of ML algorithms? Give an example of each.

Ans.

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

View 1 answer

Q18. Explain logic of quick sort

Ans.

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

Add your answer
Frequently asked in

Q19. Write a code to find if two words are anagrams

Ans.

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

View 4 more answers
Frequently asked in

Q20. Fill up numbers from 1-25 in a 5X5 matrix such that each number is average of the adjacent numbers

Ans.

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

Add your answer

Q21. Write a fibanocci or simple coding question

Ans.

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

Add your answer
Frequently asked in

Q22. The number of swapping operations required to sort the array [8,22,7,9,31,19,5,13] in bubblesort?

Ans.

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

Add your answer

Q23. How RPN is calculated

Ans.

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

Add your answer

Q24. What is the key of remove duplicates

Ans.

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.

View 3 more answers

Q25. Write program to find even and odd number using lambda expression

Ans.

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

Add your answer
Frequently asked in

Q26. What is the difference between BFS and DFS

Ans.

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

Add your answer

Q27. Find count of words in a sentence using Map

Ans.

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

Add your answer

Q28. Find all permutations of a given string. (Not in lexicographic order)

Ans.

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.

Add your answer
Frequently asked in

Q29. implement bfs in graph

Ans.

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

View 1 answer
Frequently asked in

Q30. explain all the serach algorithm you know with space and Time complexities

Ans.

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

Add your answer
Frequently asked in

Q31. Write code to find max length subarray matching the given sum

Ans.

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

Add your answer
Frequently asked in

Q32. Q2. Write insertion sort algo.

Ans.

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)

Add your answer

Q33. Find longest increasing sequence in a matrix

Ans.

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

View 1 answer

Q34. 3. Check if two strings are anagram

Ans.

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

Add your answer

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

Ans.

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

Add your answer

Q36. What is Mmeomization?

Ans.

Memoization is a technique used in programming to optimize performance by storing the results of expensive function calls and returning the cached result when the same inputs occur again.

  • Memoization helps reduce redundant calculations by storing the results of function calls in a cache

  • It is commonly used in dynamic programming and recursive algorithms to improve performance

  • Example: Fibonacci sequence calculation can be optimized using memoization to store previously calculate...read more

Add your answer

Q37. What is the best approach to find the missing number from set of consecutive n numbers

Ans.

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.

View 1 answer

Q38. Get 2 nd max element from array

Ans.

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

Add your answer

Q39. What is Min-Cut placement algorithm? Given some block sizes, use the algorithm to place them on a given chip area

Ans.

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

Add your answer
Frequently asked in

Q40. find out the subset of an array of continuous positive numbers from a larger array whose sum of of the elements is larger in comparision to other subset. eg: {1,2 5 -7, 2 5} .The two subarrays are {1,2,5} {2,5}...

read more
Ans.

Find the subset of an array with the largest sum of continuous positive numbers.

  • Iterate through the array and keep track of the current sum and the maximum sum seen so far.

  • If the current element is positive, add it to the current sum. If it is negative, reset the current sum to 0.

  • Also keep track of the start and end indices of the maximum sum subset.

  • Return the subset using the start and end indices.

Add your answer
Frequently asked in

Q41. write a program to print name?

Ans.

A program to print name using an array of strings.

  • Declare an array of strings with the name.

  • Assign the name to the array.

  • Loop through the array and print each string.

Add your answer
Frequently asked in

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

Ans.

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

Add your answer

Q43. Find the maximum sum of the subarrays in an array.

Ans.

Find the maximum sum of subarrays in an array.

  • Iterate through the array and keep track of the current sum.

  • If the current sum becomes negative, reset it to 0.

  • Update the maximum sum as you iterate through the array.

  • Return the maximum sum found.

Add your answer

Q44. Find sub-matrix from a matrix of both positive and negative numbers with maximum sum.

Ans.

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.

Add your answer

Q45. What are the different types of complexities?

Ans.

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

Add your answer
Frequently asked in

Q46. Given a map of coffee shops and a person on the map give the closest n coffee shops to him

Ans.

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.

Add your answer
Frequently asked in

Q47. Build a function that returns the Fibonacci series of N elements

Ans.

Function to return Fibonacci series of N elements

  • Create an array to store the series

  • Use a loop to generate the series

  • Return the array

Add your answer
Frequently asked in

Q48. sort the elements of an unsorted array

Ans.

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.

Add your answer

Q49. Maximum Sum BST Problem Statement

You are presented with a Binary Tree 'root', which may not necessarily be a Binary Search Tree (BST). Your objective is to identify the maximum sum of node values in any subtre...read more

Ans.

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

Add your answer

Q50. Program to find the number of trailing zeros in a factorial

Ans.

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

Add your answer
Frequently asked in

Q51. Array Intersection Problem Statement

Given two integer arrays/ lists ARR1 and ARR2 of sizes N and M respectively, you are required to determine their intersection. An intersection is defined as the set of commo...read more

Ans.

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

View 2 more answers

Q52. Find a index value present an array

Ans.

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.

Add your answer

Q53. Find median of two sorted arrays. O(logM + logN)

Ans.

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

Add your answer

Q54. 1. What is efficiency

Ans.

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

Add your answer

Q55. Write the algorithm for reversing the string

Ans.

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.

View 3 more answers
Frequently asked in

Q56. find if number i power of 2

Ans.

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.

View 2 more answers
Frequently asked in

Q57. Count the frequency of elements in an array

Ans.

Count frequency of elements in an array of strings

  • Create a dictionary to store element frequency

  • Loop through array and update dictionary

  • Return dictionary

Add your answer

Q58. Find nearest index of character in string for each index.

Ans.

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.

Add your answer

Q59. Connect Ropes with Minimum Cost

Given 'N' ropes, each having different lengths, your task is to connect these ropes into one single rope. The cost to connect two particular ropes is equal to the sum of their le...read more

Ans.

The task is to connect N ropes into one rope with minimum cost.

  • Sort the array of rope lengths in ascending order.

  • Initialize a variable to keep track of the total cost.

  • While there are more than one rope, take the two shortest ropes and connect them.

  • Add the cost of connecting the two ropes to the total cost.

  • Replace the two shortest ropes with the connected rope.

  • Repeat the above steps until only one rope remains.

  • Return the total cost.

Add your answer

Q60. What is the best search of practice

Ans.

The best search practice for a security guard is thorough and systematic to ensure all areas are properly checked.

  • Perform a systematic search of all designated areas

  • Use proper search techniques such as grid search or spiral search

  • Be thorough and pay attention to detail to ensure nothing is missed

  • Document the search process and any findings for record keeping purposes

View 1 answer
Frequently asked in

Q61. How to find the duplicate?

Ans.

To find duplicates, compare each element with all other elements and mark the duplicates.

  • Iterate through the array and compare each element with all other elements

  • If a duplicate is found, mark it or remove it

  • Use a hash table or set to keep track of seen elements for faster lookup

  • For large datasets, consider sorting the array and then finding duplicates

  • Examples: comparing strings in an array, finding duplicate numbers in a list

Add your answer

Q62. - Find all distinct elements in a list

Ans.

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

Add your answer

Q63. Was asked to design an algorithm for the snake and ladders game.

Ans.

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

Add your answer

Q64. 9)how to avoid hash collision

Ans.

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

Add your answer

Q65. Write optimized code of Prime Number(on paper)

Ans.

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

Add your answer

Q66. How to Remove duplicate element from an array

Ans.

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

Add your answer

Q67. How will you rotate matrix by 90 degrees clockwise and anticlockwise?

Ans.

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

Add your answer
Frequently asked in

Q68. What are the different sorting technique?

Ans.

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

Add your answer
Frequently asked in

Q69. An unsorted array has numbers. Find the duplicate numbers and return the array.

Ans.

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.

Add your answer
Frequently asked in

Q70. Valid Sudoku Problem Statement

You are given a 9 X 9 2D matrix named MATRIX which contains some cells filled with digits (1 to 9) and some cells left empty (denoted by 0).

Your task is to determine if there is ...read more

Ans.

The task is to determine if a given 9x9 matrix can be filled with digits 1-9 to form a valid Sudoku solution.

  • Iterate through each cell in the matrix.

  • For each empty cell, try filling it with a digit from 1-9 and check if it satisfies the Sudoku conditions.

  • Use helper functions to check if the digit is valid in the current row, column, and sub-matrix.

  • If a valid digit is found, recursively fill the next empty cell.

  • If all cells are filled and the Sudoku conditions are satisfied, r...read more

Add your answer

Q71. Remove duplicates without using inbuilt methods

Ans.

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

Add your answer

Q72. Given two sequences of length N, how to find the max window of matching patterns. The patterns can be mutated

Ans.

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

Add your answer
Frequently asked in

Q73. Find if a given directed graph is cyclic or not

Ans.

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

Add your answer

Q74. draw a flow chart to find if a no is even or not

Ans.

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

Add your answer
Frequently asked in

Q75. What is a Brute Force Algorithm?

Ans.

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.

Add your answer
Frequently asked in

Q76. 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)?

Ans.

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

Add your answer
Frequently asked in

Q77. What is logic of amstrong number say its coding logic

Ans.

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.

View 1 answer

Q78. What is GCD? Explain in details

Ans.

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.

View 2 more answers

Q79. rotate a array k times

Ans.

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

Add your answer
Frequently asked in

Q80. Which is the best and less time consuming way to calculate factorial of a number?

Ans.

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

View 3 more answers

Q81. Print first duplicate value in a string.

Ans.

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.

Add your answer

Q82. What are Fto searches and how it help the client?

Ans.

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

Add your answer

Q83. Explian meaning of analysis

Ans.

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.

Add your answer

Q84. validate if string containg "{" and "}" are balanced or not

Ans.

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

Add your answer

Q85. Write a pseudo code to find the k'th largest element in a array

Ans.

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

Add your answer
Frequently asked in

Q86. Order of People Heights Problem Statement

Consider 'N' individuals numbered from 0 to N-1 standing in a queue. You are provided with two arrays: Height and Infront, each consisting of 'N' non-negative integers....read more

Ans.

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

Add your answer
Frequently asked in

Q87. Find the total no of the island in a 2d matrix. Working code was required.

Ans.

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.

Add your answer
Frequently asked in

Q88. Write code for QuickSort

Ans.

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

Add your answer

Q89. 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 more
Ans.

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

Add your answer

Q90. find pair which have a given sum in a given array

Ans.

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.

Add your answer

Q91. 1. Write a code to reverse a linked list?

Ans.

Code to reverse a linked list

  • Create three pointers: prev, curr, and next

  • Initialize prev to null and curr to head

  • Loop through the list and set next to curr's next node

  • Set curr's next node to prev

  • Move prev and curr one node ahead

  • Return prev as the new head

Add your answer
Frequently asked in

Q92. What is route planning or optimization?

Ans.

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

View 1 answer
Frequently asked in

Q93. Find Peak Element and majority element

Ans.

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

Add your answer
Frequently asked in

Q94. find tree node from leet code

Ans.

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

Add your answer
Frequently asked in

Q95. Tell me something about heap sort

Ans.

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

Add your answer

Q96. Find 3 nos a,b and c in an array where a+b = c

Ans.

Find 3 numbers in an array where a+b=c.

  • Loop through the array and check for all possible combinations of a and b.

  • Use a hash table to store the values of a and b, and check if c is present in the hash table.

  • Sort the array and use two pointers to find a and b, and then check if their sum equals c.

Add your answer
Frequently asked in

Q97. write the code for the matrix multiplication

Ans.

Matrix multiplication code implementation in C++

  • Declare two matrices A and B of appropriate sizes

  • Iterate through rows and columns to calculate each element of the resulting matrix C

  • Use nested loops for efficient computation

  • Ensure the number of columns in matrix A is equal to the number of rows in matrix B

Add your answer

Q98. Find if a given string exists in a given matrix of characters

Ans.

Find if a given string exists in a given matrix of characters

  • Iterate through each character in the matrix and check if it matches the first character of the given string. If it does, perform a depth-first search to check if the rest of the string can be formed from adjacent characters in the matrix.

  • Use a trie data structure to store all possible substrings of the matrix and check if the given string is present in the trie.

  • Convert the matrix into a string and use string search...read more

Add your answer

Q99. Write an algorithm to select the number between min and maximum from a number series and that number shouldn't be a multiple of 10

Ans.

Algorithm to select a non-multiple of 10 from a number series between min and max

  • Loop through the number series from min to max

  • Check if the current number is a multiple of 10

  • If not, select the number and exit the loop

  • If all numbers are multiples of 10, return an error message

View 2 more answers
Frequently asked in

Q100. Divide the array in two Halves and keep each half in ascending order without using new Array?

Ans.

Divide array in two halves and keep each half in ascending order without using new Array.

  • Use Array.sort() method to sort the original array

  • Use Array.slice() method to divide the array into two halves

  • Use Array.reverse() method to reverse the second half of the array

Add your answer
1
2
3
Interview Tips & Stories
Ace your next interview with expert advice and inspiring stories

Interview experiences of popular companies

3.7
 • 10.4k Interviews
3.6
 • 7.6k Interviews
3.7
 • 5.6k Interviews
3.8
 • 5.6k Interviews
4.1
 • 5k Interviews
3.7
 • 4.8k Interviews
3.7
 • 897 Interviews
3.5
 • 408 Interviews
3.9
 • 250 Interviews
View all
Algorithms Interview Questions
Share an Interview
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
70 Lakh+

Reviews

5 Lakh+

Interviews

4 Crore+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter