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

Q3. Alternate Print Problem Statement

Given two strings A and B, your task is to print these two strings in an alternating sequence by indices. That is, the first character of 'A', the first character of 'B', follo...read more

Ans.

The task is to print two strings in an alternating sequence by indices.

  • Iterate through both strings simultaneously and append characters alternately

  • Handle the case where one string is longer than the other

  • Use two pointers to keep track of the current index in each string

Add your answer
right arrow
Frequently asked in
Q4. The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order.
Ans.

The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence with increasing order.

  • Use dynamic programming to solve the LIS problem efficiently.

  • Maintain an array to store the length of the LIS ending at each element.

  • Iterate through the array and update the LIS length based on previous elements.

  • Example: For input [10, 22, 9, 33, 21, 50, 41, 60, 80], the LIS is [10, 22, 33, 50, 60, 80] with length 6.

Add your answer
right arrow
Frequently asked in
Are these interview questions helpful?

Q5. Remove Duplicates from a Sorted Array

Given a sorted integer array ARR of size N, you need to remove duplicates such that each element appears only once and return the length of this new array.

Input:

The first...read more
Ans.

Remove duplicates from a sorted array in-place and return the length of the modified array.

  • Use two pointers approach to track unique elements and duplicates.

  • Modify the input array in-place without using extra space.

  • Return the length of the modified array.

Add your answer
right arrow
Q6. You are given a string. What is the minimum number of characters that need to be inserted to convert it into a palindrome?
Ans.

The minimum number of characters needed to convert a string into a palindrome is the length of the string minus the length of the longest palindromic subsequence of the string.

  • Find the longest palindromic subsequence of the given string.

  • Subtract the length of the longest palindromic subsequence from the length of the original string to get the minimum number of characters needed to convert it into a palindrome.

Add your answer
right arrow
Frequently asked in
Share interview questions and help millions of jobseekers 🌟

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

Q8. Strings of Numbers Problem Statement

You are given two integers 'N' and 'K'. Consider a set 'X' of all possible strings of 'N' number of digits where all strings only contain digits ranging from 0 to 'K' inclus...read more

Ans.

The task is to find a string of minimal length that includes every possible string of N digits with digits ranging from 0 to K as substrings.

  • Generate all possible strings of N digits with digits from 0 to K

  • Concatenate these strings in a way that all are substrings of the final string

  • Return 1 if the final string contains all possible strings, else return 0

Add your answer
right arrow
Frequently asked in

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. Largest Cycle in Maze Problem Statement

Given a maze represented by 'N' cells numbered from 0 to N-1, and an array arr of 'N' integers where arr[i] denotes the cell number that can be reached from the 'i'-th ce...read more

Ans.

Identify the length of the largest cycle in a maze represented by cells and an array of integers.

  • Iterate through each cell and find the cycle length using DFS or Floyd's Tortoise and Hare algorithm.

  • Handle self-cycles and cells with no exit by checking arr[i] = i and arr[i] = -1 respectively.

  • Output the length of the largest cycle found or -1 if no cycles exist.

Add your answer
right arrow

Q10. Problem: kth Missing Element in a Sequence

Given a strictly increasing sequence of integers VEC, identify the Kth missing contiguous integer element that is not present in the sequence, starting from the leftmo...read more

Ans.

Find the kth missing element in a sequence of integers.

  • Iterate through the sequence to find missing elements.

  • Keep track of the count of missing elements found.

  • Return the kth missing element once count reaches k.

Add your answer
right arrow

Q11. 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
right arrow
Frequently asked in

Q12. Constellation Identification Problem

Given a matrix named UNIVERSE with 3 rows and 'N' columns, filled with characters {#, *, .}, where:

  • '*' represents stars.
  • '.' represents empty space.
  • '#' represents a separ...read more
Ans.

The task is to identify constellations shaped like vowels within a matrix filled with characters {#, *, .}.

  • Iterate through the matrix to find 3x3 constellations shaped like vowels.

  • Check for vowels 'A', 'E', 'I', 'O', 'U' in the constellations.

  • Print the vowels found in each test case.

View 3 more answers
right arrow
Frequently asked in

Q13. 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
right arrow

Q14. 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
right arrow

Q15. Number of Mismatching Bits

Determine the number of bits that differ between the binary representations of two given integers "first" and "second".

Input:

The input starts with an integer ‘T’ representing the nu...read more
Ans.

Calculate the number of mismatching bits between two given integers in their binary representation.

  • Convert the integers to binary representation using bitwise operations.

  • Count the number of differing bits by comparing the binary representations.

  • Return the count of mismatching bits for each test case.

Add your answer
right arrow
Frequently asked in

Q16. Maximum 0-1 Distance Problem Statement

Given a binary matrix of size N*M, find the maximum distance 'di' for every 0-cell to its nearest 1-cell, where the distance is measured using Manhattan distance. The task...read more

Ans.

Find the maximum Manhattan distance from a 0-cell to its nearest 1-cell in a binary matrix.

  • Iterate through the matrix to find all 0-cells and calculate their distances to nearest 1-cells using Manhattan distance formula

  • Keep track of the maximum distance found so far and update it if a larger distance is encountered

  • Return the maximum distance as the final result

Add your answer
right arrow

Q17. 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
right arrow
Frequently asked in

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

Q19. 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
right arrow

Q20. 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
right arrow
Frequently asked in

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

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

Q23. 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
right arrow
Frequently asked in

Q24. 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
right arrow
Frequently asked in

Q25. 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
right arrow
Frequently asked in

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

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

Q28. Ninja and the New Year Guests Problem

Ninja has organized a new year party and wants to verify if the guests are programmers by challenging them with a coding task. As an invited programmer, you're tasked to so...read more

Ans.

Compute the number of valid permutations of integers from 0 to N-1 such that at least K positions satisfy ARR[I] = I.

  • Use dynamic programming to solve the problem efficiently.

  • Consider the cases where K is equal to N or N-1 separately.

  • Modulo the result by 10^9 + 7 to avoid overflow issues.

Add your answer
right arrow
Frequently asked in

Q29. Matrix Median Problem Statement

You are provided with a matrix containing 'N' rows and 'M' columns filled with integers. Each row is sorted in non-decreasing order. Your task is to find the overall median of th...read more

Ans.

Find the overall median of a matrix with sorted rows.

  • Merge all elements of the matrix into a single sorted array

  • Calculate the median of the merged array

  • Handle odd number of elements by directly finding the middle element

Add your answer
right arrow

Q30. 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
right arrow
Q31. Given an array of size n, how would you find the smallest subarray that contains k distinct values?
Ans.

Use sliding window technique to find smallest subarray with k distinct values.

  • Use a sliding window approach to keep track of the subarray with k distinct values.

  • Use a hashmap to store the frequency of each element in the window.

  • Slide the window to the right until the hashmap contains k distinct elements.

  • Shrink the window from the left while maintaining k distinct elements.

  • Update the minimum subarray length as you slide the window.

  • Return the smallest subarray length found.

  • Exam...read more

Add your answer
right arrow
Frequently asked in

Q32. Next Smaller Element Problem Statement

You are provided with an array of integers ARR of length N. Your task is to determine the next smaller element for each array element.

Explanation:

The Next Smaller Elemen...read more

Ans.

Find the next smaller element for each element in an array.

  • Iterate through the array from right to left and use a stack to keep track of elements.

  • Pop elements from the stack until a smaller element is found or the stack is empty.

  • If a smaller element is found, that is the next smaller element. If the stack is empty, there is no smaller element.

Add your answer
right arrow
Frequently asked in

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

Q34. Set Matrix Zeros Problem Statement

Given an N x M integer matrix, if an element is 0, set its entire row and column to 0's, and return the matrix. Specifically, if a cell has a value 0 (i.e., matrix[i][j] == 0)...read more

Ans.

To solve the Set Matrix Zeros problem, we can use O(1) space by utilizing the first row and column to store information about zeros in the rest of the matrix.

  • Iterate through the matrix and use the first row and column to mark rows and columns that need to be zeroed out.

  • After marking, iterate through the matrix again and zero out the rows and columns based on the marks in the first row and column.

  • Remember to handle the special case of the first row and column separately.

  • Exampl...read more

View 2 more answers
right arrow
Frequently asked in

Q35. Max Element After Update Operations

Given an array A of size N, initialized with all zeros, and another array ARR of M pairs of integers representing operations. Each operation consists of a range where each el...read more

Ans.

Find the maximum element in an array after performing a series of increment operations on specified ranges.

  • Initialize an array of size N with all zeros

  • Iterate through the operations and increment elements within specified ranges

  • Return the maximum element in the array after all operations

Add your answer
right arrow
Frequently asked in

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

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

Q38. 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
right arrow
Frequently asked in

Q39. Explain BFS and DFS

Ans.

BFS and DFS are graph traversal algorithms used to search for nodes in a graph.

  • BFS stands for Breadth First Search and explores all the nodes at the current depth before moving to the next level.

  • DFS stands for Depth First Search and explores as far as possible along each branch before backtracking.

  • BFS uses a queue data structure while DFS uses a stack or recursion.

  • BFS is useful for finding the shortest path in an unweighted graph while DFS is useful for topological sorting an...read more

Add your answer
right arrow

Q40. 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
right arrow

Q41. Intersection of Two Arrays II

Given two integer arrays ARR1 and ARR2 of size N and M respectively, find the intersection of these arrays. An intersection refers to elements that appear in both arrays.

Note:
Inp...read more
Ans.

Find the intersection of two integer arrays in the order they appear in the first array.

  • Iterate through the first array and store elements in a hashmap with their frequencies.

  • Iterate through the second array and check if the element exists in the hashmap, decrement frequency if found.

  • Return the elements that have non-zero frequencies as the intersection.

Add your answer
right arrow
Frequently asked in

Q42. 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
right arrow
Frequently asked in

Q43. 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
right arrow

Q44. Connect Ropes Problem Statement

Given a number of ropes denoted as 'N' and an array containing the lengths of these ropes, your task is to connect the ropes into one single rope. The cost to connect two ropes i...read more

Ans.

The task is to find the minimum cost required to connect all the ropes by summing their lengths.

  • Iterate through the ropes and connect the two shortest ropes at each step to minimize cost

  • Use a priority queue to efficiently find the shortest ropes

  • Keep track of the total cost as you connect the ropes

  • Example: For input [4, 3, 2, 6], connect 2 and 3 (cost 5), then connect 4 and 5 (cost 9), then connect 9 and 6 (cost 15) for a total cost of 29

View 1 answer
right arrow

Q45. Write an algorithm to find the absolute max subsequence of an array containing both positive and negative numbers in O(n) time ?

Ans.

Algorithm to find absolute max subsequence of an array with positive and negative numbers in O(n) time.

  • Initialize max_so_far and max_ending_here as 0

  • Loop through the array and for each element, add it to max_ending_here

  • If max_ending_here becomes negative, reset it to 0

  • If max_ending_here is greater than max_so_far, update max_so_far

  • Return max_so_far

Add your answer
right arrow
Frequently asked in

Q46. 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
right arrow
Frequently asked in

Q47. Maximum Subarray Sum Queries

You are provided with an array of ‘N’ integers and ‘Q’ queries. Each query requires calculating the maximum subarray sum in a specified range of the array.

Input:

The first line con...read more
Ans.

Implement a function to calculate maximum subarray sum queries in a given range of an array.

  • Iterate through each query and calculate the maximum subarray sum within the specified range using Kadane's algorithm.

  • Keep track of the maximum sum found so far and update it as needed.

  • Return the maximum subarray sum for each query in the test case.

Add your answer
right arrow

Q48. 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
right arrow

Q49. 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
right arrow

Q50. Count Palindromic Substrings Problem Statement

Given a string STR, determine the total number of palindromic substrings within STR.

Input:

The first line contains an integer 't' representing the number of test ...read more
Ans.

Count the total number of palindromic substrings in a given string.

  • Iterate through each character in the string and expand around it to find palindromic substrings.

  • Use dynamic programming to store previously calculated palindromic substrings.

  • Consider both odd and even length palindromes while counting.

  • Example: For input 'abbc', palindromic substrings are ['a', 'b', 'b', 'c', 'bb']. Total count is 5.

Add your answer
right arrow

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

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

Q53. Find Permutation Problem Statement

Given an integer N, determine an array of size 2 * N that satisfies the following conditions:

  1. Each number from 1 to N appears exactly twice in the array.
  2. The distance between...read more
Ans.

The task is to find a permutation array of size 2*N with specific conditions.

  • Create an array of size 2*N to store the permutation.

  • Ensure each number from 1 to N appears exactly twice in the array.

  • Check that the distance between the second and first occurrence of each number is equal to the number itself.

  • Return the array if conditions are met, else return an empty array.

Add your answer
right arrow
Frequently asked in

Q54. 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
right arrow
Frequently asked in

Q55. 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
right arrow

Q56. Maximum Sum of Products for Array Rotations

You are given an array ARR consisting of N elements. Your task is to determine the maximum value of the summation of i * ARR[i] among all possible rotations of ARR. R...read more

Ans.

Find the maximum sum of products for array rotations.

  • Iterate through all possible rotations of the array and calculate the sum of products for each rotation.

  • Keep track of the maximum sum of products found so far.

  • Return the maximum sum of products obtained.

Add your answer
right arrow
Frequently asked in

Q57. Index of First Occurrence Problem Statement

Given two strings A and B, determine the index of the first occurrence of A in B. If A is not present in B, return -1.

Example:

Input:
A = "bc", B = "abcddbc"
Output:...read more
Ans.

Find the index of the first occurrence of string A in string B.

  • Iterate through string B and check if a substring of length equal to A matches A.

  • Return the index of the first occurrence of A in B, or -1 if not found.

View 1 answer
right arrow
Frequently asked in

Q58. 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
right arrow
Frequently asked in

Q59. Calculate Score of Balanced Parentheses

In this intellectual game, Ninja is provided with a string of balanced parentheses called STR. The aim is to calculate the score based on specific game rules. If Ninja wi...read more

Ans.

Calculate the score of a string of balanced parentheses based on specific game rules.

  • Iterate through the string and keep track of the score based on the rules provided

  • Use a stack to keep track of the scores of valid parentheses expressions

  • For each '()', increment the score by 1; for '(x)', double the score of x

  • Return the final computed score for the string

Add your answer
right arrow
Frequently asked in

Q60. GCD (Greatest Common Divisor) Problem Statement

You are given two numbers, X and Y. Your task is to determine the greatest common divisor of these two numbers.

The Greatest Common Divisor (GCD) of two integers ...read more

Ans.

The greatest common divisor (GCD) of two numbers is the largest positive integer that divides both numbers without leaving a remainder.

  • Use Euclidean algorithm to find GCD efficiently

  • GCD(X, Y) = GCD(Y, X % Y)

  • Repeat until Y becomes 0, then X is the GCD

Add your answer
right arrow

Q61. 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
right arrow
Frequently asked in

Q62. 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
right arrow
Frequently asked in

Q63. 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
right arrow

Q64. Search in a 2D Matrix

Given a 2D matrix MAT of size M x N, where M and N represent the number of rows and columns respectively. Each row is sorted in non-decreasing order, and the first element of each row is g...read more

Ans.

Implement a function to search for a given integer in a 2D matrix with specific properties.

  • Iterate through each row of the matrix and perform a binary search on each row to find the target integer.

  • Since the rows are sorted, binary search can be applied efficiently to determine if the target exists in the matrix.

  • Handle edge cases such as empty matrix or invalid input values.

  • Return 'TRUE' if the target is found in the matrix, otherwise return 'FALSE'.

Add your answer
right arrow

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

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

Q67. 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
right arrow
Frequently asked in

Q68. Duplicate Elements in Array

You are provided with an array or list called ARR, consisting of N integers. These integers fall within the range from 0 to N - 1. Some elements in this array may appear more than on...read more

Ans.

Identify duplicate elements in an array of integers within the range from 0 to N - 1.

  • Iterate through the array and keep track of seen elements using a hash set.

  • If an element is already in the set, it is a duplicate and can be added to the result.

  • Return the list of duplicate elements found in the array.

  • Example: For input [1, 3, 1, 3, 4], output should be ['1', '3'].

Add your answer
right arrow
Frequently asked in

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

Q70. 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
right arrow
Frequently asked in

Q71. Best Time to Buy and Sell Stock II Problem Statement

Given the stock prices for a certain number of days, represented as an array, determine the maximum profit you can achieve. You may perform as many transacti...read more

Ans.

The problem involves finding the maximum profit that can be achieved by buying and selling stocks on different days.

  • Iterate through the array of stock prices and find the local minima and maxima to calculate profit

  • Keep track of the total profit by adding the differences between consecutive maxima and minima

  • You can perform multiple transactions, so buy at each local minima and sell at each local maxima

  • Example: For prices = [7, 1, 5, 3, 6, 4], buy at 1, sell at 5, buy at 3, sel...read more

Add your answer
right arrow

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

Q73. Knapsack Problem Statement

There is a potter with a limited amount of pottery clay (denoted as 'K' units) who can make 'N' different items. Each item requires a specific amount of clay and yields a certain prof...read more

Ans.

The Knapsack Problem involves maximizing profit by choosing which items to make with limited resources.

  • Understand the problem statement and constraints provided.

  • Implement a dynamic programming solution to solve the Knapsack Problem efficiently.

  • Iterate through the items and clay units to calculate the maximum profit that can be achieved.

  • Consider both the clay requirement and profit of each item while making decisions.

  • Ensure the solution runs within the given time limit of 1 se...read more

View 1 answer
right arrow
Frequently asked in

Q74. 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
right arrow

Q75. Space Survival Game Challenge

Ninja is in space with unlimited fuel in his super spaceship. He starts with a health level H and his spaceship has an armour A. Ninja can be on only one of the three planets at a ...read more

Ans.

Calculate the maximum time Ninja can survive in a space survival game challenge.

  • Create a function that takes initial health and armour as input for each test case

  • Simulate Ninja's movement between planets and update health and armour accordingly

  • Keep track of the maximum time Ninja can survive before health or armour reaches 0

Add your answer
right arrow
Frequently asked in,

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

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

Q78. 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
right arrow
Frequently asked in

Q79. TELL ME SOMETHING ABOUT NMST

Ans.

NMST stands for National Mathematics and Science Talent Examination.

  • NMST is a competitive exam conducted for students in the field of mathematics and science.

  • It aims to identify and nurture talented students in these subjects.

  • The exam is open to students from various educational boards and schools.

  • NMST provides a platform for students to showcase their skills and knowledge.

  • Top performers in NMST are often awarded scholarships and recognition.

Add your answer
right arrow

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

Q81. 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
right arrow
Frequently asked in

Q82. Square Root of an Integer Challenge

Given an integer 'A', the objective is to find the largest non-negative integer whose square is less than or equal to 'A'.

The square of a number is defined as the product of...read more

Ans.

Find the largest non-negative integer whose square is less than or equal to a given integer.

  • Use binary search to efficiently find the square root of the given integer.

  • Start with a range from 0 to the given integer and iteratively narrow down the range based on the square of the middle value.

  • Return the largest integer whose square is less than or equal to the given integer.

Add your answer
right arrow

Q83. Find Pair Sum Equal to K

Given an integer array arr and an integer 'Sum', find and return the total number of pairs in the array which, when added together, result in the 'Sum'.

Note:
The array can contain dupl...read more
Ans.

Find total number of pairs in array that sum to given value.

  • Use a hashmap to store frequency of each element in the array.

  • Iterate through the array and check if (Sum - current element) exists in the hashmap.

  • Increment count of pairs if found and update hashmap accordingly.

Add your answer
right arrow

Q84. Two Sum Problem Statement

Given an array A of size N, sorted in non-decreasing order, return two distinct indices whose values add up to a given 'target'. The array is 0 indexed. If multiple answers exist, retu...read more

Ans.

Given a sorted array, find two distinct indices whose values add up to a given target.

  • Use two pointers approach to find the indices that add up to the target.

  • Start with one pointer at the beginning and another at the end of the array.

  • Move the pointers towards each other based on the sum of their values compared to the target.

Add your answer
right arrow
Q85. ...read more

Distinct Subarrays with At Most K Odd Elements

Given an array A of N integers, determine the total number of distinct subarrays that contain at most K odd elements.

Example:

Input:
A = [3, 2, 3], K = 1
Output:
Ans.

Count the total number of distinct subarrays with at most K odd elements in an array.

  • Iterate through all subarrays and count the number of odd elements in each subarray.

  • Use a hashmap to keep track of the count of distinct subarrays with at most K odd elements.

  • Return the total count of distinct subarrays for each test case.

Add your answer
right arrow

Q86. Painter's Partition Problem

You are given an array/list of length 'N'. Each element of the array/list represents the length of a board. There are 'K' painters available to paint these boards. Each unit of a boa...read more

Ans.

Find the minimum time required for 'K' painters to paint 'N' boards with given lengths.

  • Use binary search to find the minimum and maximum possible time to paint all boards.

  • Iterate through the possible time range and check if it is feasible to paint all boards within that time.

  • Keep track of the number of painters used and update the time range accordingly.

Add your answer
right arrow
Frequently asked in

Q87. IP Address Formation from String

Given a string S consisting only of digits from 0 to 9, your task is to find all potential IP addresses that can be formed from S and list them in lexicographical order. If it's...read more

Ans.

Given a string of digits, find all potential valid IP addresses that can be formed from it.

  • Split the string into four parts and check if each part is a valid IP segment (0-255).

  • Use backtracking to generate all possible combinations of valid IP addresses.

  • Ensure that the IP address does not contain leading zeroes.

  • Return the valid IP addresses in lexicographical order.

Add your answer
right arrow

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

Q89. Find all subsets of a number set such that sum of these numbers is equal to a given number

Ans.

Find all subsets of a number set with a given sum

  • Use a recursive approach to generate all possible subsets

  • For each subset, calculate the sum and check if it matches the given number

  • Store the subsets that satisfy the condition

Add your answer
right arrow
Frequently asked in

Q90. Given an array of integers, find Pythagorean triplets. i.e. find a,b and c which satisfies a^2 + b^2 = c^2. Integers could be positive or negative

Ans.

Find Pythagorean triplets in an array of integers.

  • Loop through the array and pick two numbers at a time.

  • Calculate the sum of squares of the two numbers.

  • Check if the sum is a perfect square.

  • If yes, then it is a Pythagorean triplet.

  • Repeat until all possible combinations are checked.

Add your answer
right arrow
Frequently asked in

Q91. 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
right arrow

Q92. Version Comparison

Given two strings, Version1 and Version2, each representing version numbers, determine which one is the latest version.

Explanation:

The input strings consist of digits and dots only. Both st...read more

Ans.

Compare two version numbers to determine the latest version.

  • Split the version numbers by '.' and compare each part from left to right.

  • If a part in Version2 is greater than the corresponding part in Version1, Version2 is the latest.

  • Handle cases where one version number has more parts than the other.

  • Return 1 if Version1 is the latest, -1 if Version2 is the latest, and 0 if they are the same.

Add your answer
right arrow
Frequently asked in

Q93. Counting Pairs Problem Statement

Given a positive integer N, determine the count of all possible positive integral pairs (X, Y) that satisfy the equation 1/X + 1/Y = 1/N.

Example:

Input:
T = 1
N = 2
Output:
3
Ex...read more
Ans.

Count the number of positive integral pairs (X, Y) that satisfy the given equation.

  • Iterate through all possible values of X and calculate corresponding Y to check if the equation is satisfied.

  • Optimize the solution by considering the constraints and properties of the equation.

  • Handle special cases like when N is 1 or when X and Y are equal.

  • Use mathematical properties to reduce the number of calculations needed.

  • Consider edge cases like when N is a prime number.

Add your answer
right arrow

Q94. Graph Coloring Problem

You are given a graph with 'N' vertices numbered from '1' to 'N' and 'M' edges. Your task is to color this graph using two colors, such as blue and red, in a way that no two adjacent vert...read more

Ans.

Given a graph with 'N' vertices and 'M' edges, determine if it can be colored using two colors without adjacent vertices sharing the same color.

  • Use graph coloring algorithm like BFS or DFS to check if the graph can be colored with two colors without conflicts.

  • Check if any adjacent vertices have the same color. If so, it is not possible to color the graph as described.

  • If the graph has connected components, color each component separately to determine if the entire graph can be...read more

Add your answer
right arrow

Q95. Job Scheduling Problem

You are provided with a list of jobs, where each job has a specific deadline and profit. The goal is to schedule these jobs such that the total profit is maximized. Each job requires exac...read more

Ans.

The goal is to schedule jobs to maximize profit while meeting deadlines. Each job takes one unit of time and only one job can be scheduled at a time.

  • Sort the jobs in decreasing order of profit

  • Iterate through the sorted jobs and schedule them based on their deadlines

  • Keep track of the total profit achieved

  • Ensure each job is completed before its deadline

Add your answer
right arrow
Frequently asked in

Q96. - 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
right arrow
Q97. How can you check if two strings are anagrams of each other?
Ans.

Check if two strings are anagrams by comparing the sorted versions of the strings.

  • Sort both strings and compare if they are equal.

  • Use a hashmap to store the frequency of characters in each string and compare the maps.

  • Ignore spaces and punctuation when comparing the strings.

Add your answer
right arrow

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

Q99. 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
right arrow

Q100. 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
right arrow
1
2
3
Next
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.5k Interviews
3.7
 • 5.6k Interviews
3.8
 • 5.6k Interviews
4.1
 • 5k Interviews
3.7
 • 4.7k Interviews
3.7
 • 846 Interviews
3.5
 • 376 Interviews
3.9
 • 233 Interviews
View all
Recently Viewed
JOBS
Browse jobs
Discover jobs you love
JOBS
Browse jobs
Discover jobs you love
REVIEWS
TCS
No Reviews
JOBS
Browse jobs
Discover jobs you love
DESIGNATION
DESIGNATION
SKILL
Interview Questions
223 interview questions
DESIGNATION
SKILL
Interview Questions
250 interview questions
DESIGNATION
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