Algorithms

Skill
Computer Science

Top 250 Algorithms Interview Questions and Answers 2024

250 questions found

Updated 13 Dec 2024

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

Code 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

View 2 more answers

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

Q4. Write a program to count vowels and consonants in string

Ans.

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

View 2 more answers
Are these interview questions helpful?

Q5. Write a program to check if a string is a palindrome or not.

Ans.

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.

View 1 answer

Q6. 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
Share interview questions and help millions of jobseekers 🌟

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

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

Algorithms Jobs

Software Developer Instructor- Data Structures and Algorithms 1-3 years
Nxtwave Disruptive Technologies
4.0
Karimnagar
Software Developer Instructor- Data Structures and Algorithms 1-3 years
Nxtwave Disruptive Technologies
4.0
Hyderabad / Secunderabad
Data Structures & Algorithms Consultant, Trainer & Mentor 1-4 years
Blue Lotus Technologies Pvt Ltd
5.0
Chennai

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

Q10. find the count of alphabets in a sentance

Ans.

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

Add your answer
Frequently asked in

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

Q13. 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 2 more answers
Frequently asked in

Q14. Write the code to find factorial using function recursion.

Ans.

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

View 1 answer
Q15. K-th element of 2 sorted array

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

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

View 3 more answers

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

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

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

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?

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

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

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

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

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

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

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

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

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

Q28. Swap two number without using temperory variable

Ans.

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

Add your answer
Frequently asked in

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

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

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

Q32. Write algo to mirror a given Binary Tree?

Ans.

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

Add your answer
Frequently asked in

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

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

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

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

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

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

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?

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

Q40. When to use memoisation?

Ans.

Memoisation should be used to optimize performance by caching expensive function calls.

  • Use memoisation when a function is computationally expensive and its output depends only on its input parameters.

  • Memoisation can be used to cache the results of recursive function calls to avoid redundant calculations.

  • In React, useMemo hook can be used to memoize the result of a function component to prevent unnecessary re-renders.

  • Memoisation is particularly useful in optimizing performance...read more

Add your answer

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

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

Q43. a program to print random token numbers?

Ans.

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

View 9 more answers

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

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

Q46. Find duplicate in array program

Ans.

Program to find duplicates in an array.

  • Iterate through the array and compare each element with the rest of the elements.

  • If a match is found, add it to a separate array or print it.

  • Use a hash table to keep track of the frequency of each element.

  • Sort the array and compare adjacent elements to find duplicates.

Add your answer

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

Q48. Build a pyramid pattern of numbers in O(n) time using any language.

Ans.

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.

Add your answer
Frequently asked in

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

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

Q50. Find Contiguous maximum sum from subarray of given array

Ans.

Find the maximum sum of a contiguous subarray within a given array.

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

Add your answer

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

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

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

Q54. 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
Q55. Maximum Sum BST

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

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

View 3 more answers
Q56. Array Intersection

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

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 3 more answers

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

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

Q59. Find duplicates in a string and count repeated letters

Ans.

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

View 1 answer
Frequently asked in

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

Q61. Write a code to swap to number without third variable

Ans.

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

Add your answer

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

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

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

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

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

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

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

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

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

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

Q71. 8) To write program to iterate an array using pointer

Ans.

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

View 1 answer
Frequently asked in

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

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

Q74. 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
Q75. Valid Sudoku

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

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

View 3 more answers

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

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

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

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

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

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

Q82. Write a program to reverse a n integer

Ans.

Program to reverse an integer

  • Convert the integer to a string

  • Reverse the string

  • Convert the reversed string back to an integer

Add your answer
Frequently asked in

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

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

Q85. Write a code to multiply two matrices of dimension M*N and N*K

Ans.

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

Add your answer
Frequently asked in

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

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

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

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

Q90. Given a string of paranthesis tell longest valid parantheisis

Ans.

Use stack to keep track of indices of opening parentheses, update max length when closing parentheses found

  • Use a stack to keep track of indices of opening parentheses

  • When a closing parentheses is found, update max length by calculating the difference between current index and top of stack

  • Handle edge cases like extra closing parentheses or unmatched opening parentheses

  • Example: Input: "(()()", Output: 4 (for "()()")

Add your answer
Frequently asked in

Q91. 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
Q92. Order of People Heights

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

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

View 3 more answers
Frequently asked in

Q93. How to calculate the square root of a number?? note: your compiler does not support math.h

Ans.

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

Add your answer
Frequently asked in

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

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

Q96. Write a program to print First 10 natural numbers

Ans.

Program to print first 10 natural numbers

  • Use a loop to iterate from 1 to 10

  • Print each number in the loop

View 1 answer

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

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

Q99. Burn a tree coding question

Ans.

Implement a function to burn a tree starting from a given node

  • Start by creating a function that takes in the root node of the tree and the node to start burning from

  • Use a queue to perform a level order traversal of the tree

  • Keep track of the nodes that have been burned and the nodes that are yet to be burned

Add your answer

Q100. 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
1
2
3
Interview Tips & Stories
Ace your next interview with expert advice and inspiring stories

Interview experiences of popular companies

3.7
 • 10k Interviews
3.7
 • 7.3k Interviews
3.8
 • 5.4k Interviews
3.7
 • 5.2k Interviews
4.1
 • 4.9k Interviews
3.8
 • 4.6k Interviews
3.7
 • 862 Interviews
3.6
 • 399 Interviews
4.0
 • 245 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
Get AmbitionBox app

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