Top 250 Algorithms Interview Questions and Answers

Updated 21 Jan 2025

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

Ans.

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

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

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

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

Add your answer
Frequently asked in

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

Q103. Convert int into roman number

Ans.

Convert integer to Roman numeral

  • Create an array of Roman numerals and their corresponding integer values

  • Loop through the array in reverse order and subtract the integer value from the input number until it reaches 0

  • Append the corresponding Roman numeral to the result string for each subtraction

  • Handle special cases like 4, 9, 40, 90, etc.

Add your answer

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

Ans.

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

  • Loop through the number series from min to max

  • Check if the current number is a multiple of 10

  • If not, select the number and exit the loop

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

View 2 more answers
Frequently asked in
Are these interview questions helpful?

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

Ans.

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

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

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

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

Add your answer

Q106. What is main problem in Google algorithm

Ans.

The main problem in Google algorithm is spam and low-quality content.

  • Spammy and low-quality content can manipulate search results and harm user experience.

  • Google constantly updates its algorithm to combat spam and improve search results.

  • Examples of spammy tactics include keyword stuffing, cloaking, and link schemes.

  • Low-quality content can include duplicate content, thin content, and content with little value to users.

Add your answer
Share interview questions and help millions of jobseekers 🌟

Q107. If there is an array of numbers give the sum of number of each element in array

Ans.

To find the sum of numbers in an array, loop through the array and add each element to a running total.

  • Create a variable to hold the running total

  • Loop through the array and add each element to the running total

  • Return the running total

Add your answer

Q108. how to reverse a linked list, how to reverse a string

Ans.

To reverse a linked list, traverse the list and change the direction of pointers. To reverse a string, use built-in functions or loop through the string and swap characters.

  • For reversing a linked list, use three pointers - prev, current, and next. Traverse the list and change the direction of pointers.

  • For reversing a string, use built-in functions like reverse() or loop through the string and swap characters using two pointers - one at the beginning and one at the end.

  • Example...read more

Add your answer

Algorithms Jobs

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

Q109. write program to find long unique string

Ans.

Program to find the longest unique string in an array of strings

  • Iterate through each string in the array

  • For each string, create a set to store unique characters

  • Check each character in the string and add it to the set if it's not already present

  • Keep track of the length of the current unique string and update the longest unique string found so far

  • Return the longest unique string

Add your answer

Q110. find first and last occurence of a target element in shorted array

Ans.

Find first and last occurrence of a target element in a sorted array.

  • Use binary search to find the first occurrence of the target element.

  • Modify the binary search to find the last occurrence of the target element.

  • Handle cases where the target element is not found in the array.

Add your answer

Q111. Write program to add two numbers in sequence

Ans.

Program to add two numbers in sequence

  • Declare two integer variables to store the numbers

  • Take input from user for both variables

  • Add the two variables and store the result in a third variable

  • Print the result

Add your answer

Q112. Implement multiplication without Ò€œ*Ò€ sign.

Ans.

Multiplication can be implemented using repeated addition or bitwise operations.

  • Repeated addition: add the same number repeatedly for the number of times specified by the other number.

  • Bitwise operations: use shift and add operations to perform multiplication.

  • Example: 5 * 3 can be implemented as 5 + 5 + 5 or (5 << 1) + 5.

Add your answer
Frequently asked in

Q113. How to get non repeating substring from a string

Ans.

To get non-repeating substring from a string, we can use the sliding window technique.

  • Create a hash set to store the characters in the current window.

  • Iterate through the string and add each character to the hash set.

  • If a repeating character is found, remove the first character from the hash set and move the window.

  • Keep track of the longest non-repeating substring found so far.

  • Return the longest non-repeating substring.

Add your answer
Frequently asked in

Q114. How to implement

Ans.

To implement a solution in SAP, follow these steps: analyze requirements, design solution, configure system, test, deploy, and support.

  • Analyze the business requirements to understand the scope of the solution.

  • Design the solution architecture and create a detailed plan.

  • Configure the SAP system according to the design specifications.

  • Test the solution to ensure it meets the requirements and is error-free.

  • Deploy the solution to the production environment.

  • Provide ongoing support a...read more

Add your answer
Frequently asked in

Q115. 2. Program ATM Machine To Give Only 500 And 100 And Count There Number

Ans.

Program an ATM machine to dispense only 500 and 100 notes and count their number.

  • Create a function to dispense money

  • Use a loop to count the number of notes

  • Use if statements to check if the amount is divisible by 500 or 100

  • Display the total number of notes dispensed

Add your answer

Q116. Optimize the code for job scheduling written in the first round

Ans.

Optimize job scheduling code

  • Use priority queue to efficiently schedule jobs

  • Implement dynamic programming to optimize job sequence

  • Consider parallel processing to reduce overall time

  • Use efficient data structures to store job information

Add your answer
Frequently asked in

Q117. Solve the problems: Write a formula to display A if A is present, display B if B is present else display None.

Ans.

Write a formula to display A if A is present, display B if B is present else display None.

  • Use conditional statements to check if A or B is present

  • If A is present, display A

  • If B is present, display B

  • If neither A nor B is present, display None

View 1 answer
Frequently asked in

Q118. Write a code for Octal to Decimal Conversion.

Ans.

Code for Octal to Decimal Conversion

  • Start from the rightmost digit and move towards the leftmost digit

  • Multiply each digit with 8 raised to the power of its position

  • Add all the products obtained in the previous step to get the decimal equivalent

View 1 answer
Frequently asked in
Q119. Zero Matrix

You are given a matrix 'MATRIX' of dimension 'N' x 'M'. Your task is to make all the elements of row 'i' and column 'j' equal to 0 if any element in the ith row or jth column of the matrix is 0.

Note...read more

Ans.

The task is to modify a given matrix such that if any element in a row or column is 0, then make all elements in that row and column 0.

  • Iterate through the matrix and keep track of rows and columns that contain 0s

  • After the first iteration, iterate through the tracked rows and columns and set all elements to 0

  • Handle the case where the first row or column contains 0 separately

  • To solve with O(1) space complexity, use the first row and first column of the matrix to track the rows ...read more

View 2 more answers
Frequently asked in

Q120. Print left most node of each level by doing BFs

Ans.

Print the leftmost node of each level using BFS.

  • Implement BFS algorithm to traverse the tree level by level.

  • Keep track of the leftmost node of each level.

  • Print the leftmost node of each level after traversal is complete.

Add your answer

Q121. write algorithm for swapping variables

Ans.

Algorithm for swapping variables

  • Use a temporary variable to store the value of one variable

  • Assign the value of the second variable to the first variable

  • Assign the value of the temporary variable to the second variable

Add your answer
Frequently asked in

Q122. Find the maximum for each and every contiguous subarray of size k from an arr of size n.

Ans.

Find maximum for each contiguous subarray of size k from an array of size n.

  • Iterate through the array and keep track of maximum for each subarray of size k

  • Use a sliding window approach to efficiently calculate maximum for each subarray

  • Time complexity: O(n)

  • Example: arr = [10, 5, 2, 7, 1, 9, 4], k = 3, output = [10, 7, 7, 9, 9]

Add your answer
Frequently asked in

Q123. 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
Frequently asked in

Q124. How to use boolean search?

Ans.

Boolean search is a technique used to combine keywords and operators to produce more accurate and relevant search results.

  • Use AND to narrow down search results

  • Use OR to broaden search results

  • Use NOT to exclude certain keywords

  • Use parentheses to group keywords and operators

  • Example: (Java AND Developer) OR (Python AND Engineer)

  • Example: (Marketing OR Advertising) NOT Sales

Add your answer

Q125. Write code to print bottom view of Binary Search Tree

Ans.

Print the bottom view of a Binary Search Tree.

  • Use a map to store the horizontal distance and the bottom-most node at that distance.

  • Traverse the tree in level order and update the map with each node's horizontal distance and level.

  • Print the nodes in the map in ascending order of their horizontal distance.

Add your answer

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

read more
Ans.

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

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

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

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

  • Return the subset using the start and end indices.

Add your answer
Frequently asked in

Q127. Is fft a transform by it self?

Ans.

Yes, FFT is a transform by itself.

  • FFT stands for Fast Fourier Transform

  • It is a mathematical algorithm used to transform a signal from time domain to frequency domain

  • FFT is a standalone transform and can be used for various applications such as signal processing, image processing, and data compression

Add your answer
Frequently asked in

Q128. Write Fibonacci sequence

Ans.

The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones.

  • Start with two initial numbers, 0 and 1

  • Each subsequent number is the sum of the two preceding numbers

  • Repeat this process until the desired number of terms is reached

Add your answer
Frequently asked in

Q129. Tell me the logic of reverse the number?

Ans.

Reverse the number means to get the digits in the opposite order.

  • Extract the digits of the number using modulo operator

  • Multiply the reversed number by 10 and add the next digit

  • Repeat until all digits are processed

Add your answer
Frequently asked in

Q130. Write code to check if string/Integer is palindrome or not. Example: 2R acEC ar 2 (True)

Ans.

A code to check if a given string or integer is a palindrome or not.

  • Convert the given input to a string

  • Remove any non-alphanumeric characters from the string

  • Reverse the string

  • Compare the reversed string with the original string

  • If they are the same, then the input is a palindrome

View 1 answer
Frequently asked in

Q131. Find a string in a 2D character matrix in any order(horizontal/vertical/diagonal)

Ans.

Search for a string in a 2D character matrix in any direction

  • Iterate through each cell of the matrix

  • For each cell, check all possible directions for the string

  • If found, return the starting and ending coordinates of the string

Add your answer

Q132. What is asymptotic notation ?

Ans.

Asymptotic notation is a way to describe the performance of an algorithm by analyzing its behavior as the input size approaches infinity.

  • Asymptotic notation is used to analyze the efficiency and scalability of algorithms.

  • It provides a way to compare algorithms based on their growth rates.

  • Commonly used asymptotic notations include Big O, Big Omega, and Big Theta.

  • Big O notation represents the upper bound or worst-case scenario of an algorithm's time complexity.

  • For example, an a...read more

View 2 more answers
Frequently asked in

Q133. What is Fast Fourier transform

Ans.

Fast Fourier Transform (FFT) is an algorithm used to compute the Discrete Fourier Transform (DFT) of a sequence or signal.

  • FFT is used to analyze the frequency content of a signal by decomposing it into its constituent frequencies.

  • It is commonly used in signal processing, image processing, audio analysis, and many other fields.

  • FFT algorithms are much faster than the naive DFT computation, making it practical for real-time applications.

  • Examples of applications include audio equ...read more

Add your answer

Q134. Count distinct pairs with difference equal to k and further optimize.

Ans.

Count distinct pairs with difference equal to k and optimize.

  • Use a hash set to store the elements of the array.

  • Iterate through the array and check if the current element + k or current element - k exists in the hash set.

  • Increment the count if a pair is found and add the current element to the hash set.

  • Return the count of distinct pairs.

View 2 more answers

Q135. how to find unique elements in a array?

Ans.

To find unique elements in an array, use a Set data structure.

  • Create a new Set object

  • Loop through the array and add each element to the Set

  • The Set will automatically remove duplicates, so the size of the Set will be the number of unique elements

  • Convert the Set back to an array if necessary

Add your answer

Q136. You have been given a in out time log of viewers and you need to find the highest count of viewers at any given point.

Ans.

To find highest count of viewers at any given point from in-out time log

  • Create an array of time slots with start and end time

  • Loop through the log and increment the count for each time slot

  • Track the maximum count and corresponding time slot

  • Return the time slot with highest count

Add your answer

Q137. Find duplicate character and count of given string

Ans.

Find duplicate characters and their count in a given string.

  • Create an empty dictionary to store character count

  • Iterate through the string and add characters to the dictionary

  • If character already exists in the dictionary, increment its count

  • Return the dictionary with character count

Add your answer

Q138. Print all combinations of balanced parentheses

Ans.

Print all combinations of balanced parentheses

  • Use recursion to generate all possible combinations

  • Keep track of the number of opening and closing parentheses

  • Add to the result only if the number of opening and closing parentheses are equal

Add your answer

Q139. how to find 2 nd largest number

Ans.

To find the 2nd largest number in an array, sort the array in descending order and return the element at index 1.

  • Sort the array in descending order

  • Return the element at index 1

Add your answer
Frequently asked in

Q140. 3. How you have considered the computational time?

Ans.

I have considered computational time by optimizing algorithms and using efficient data structures.

  • I have analyzed the time complexity of algorithms and chosen the most efficient ones.

  • I have used data structures like hash tables and binary trees to reduce search time.

  • I have also parallelized certain tasks to reduce overall computational time.

  • For example, in my research on image processing, I used parallel computing to speed up the process.

Add your answer

Q141. Explain different algorithms that applies in networking domain

Ans.

Algorithms used in networking include routing, switching, and security protocols.

  • Routing algorithms determine the best path for data to travel between devices on a network.

  • Switching algorithms determine how data is forwarded between network devices.

  • Security algorithms are used to protect data and prevent unauthorized access.

  • Examples of routing algorithms include OSPF and BGP.

  • Examples of switching algorithms include Spanning Tree Protocol and VLANs.

  • Examples of security algorit...read more

Add your answer
Frequently asked in

Q142. Explain all the projects and algorithms used in that projects(models)

Ans.

I have worked on various projects including developing recommendation systems, image recognition algorithms, and natural language processing models.

  • Developed recommendation system using collaborative filtering algorithm

  • Implemented image recognition algorithm using convolutional neural networks (CNN)

  • Utilized natural language processing models such as LSTM for text classification tasks

Add your answer

Q143. What were the optimisation techniques used

Ans.

Various optimisation techniques were used, including linear programming, genetic algorithms, and simulated annealing.

  • Linear programming was used to optimize resource allocation.

  • Genetic algorithms were employed for complex optimization problems.

  • Simulated annealing was utilized for finding global optima in large search spaces.

Add your answer

Q144. Check if a graph has a unique Topological sort

Ans.

A graph has a unique topological sort if and only if it is a directed acyclic graph (DAG).

  • A topological sort is a linear ordering of the vertices of a graph such that for every directed edge (u, v), vertex u comes before vertex v in the ordering.

  • To check if a graph has a unique topological sort, we can use depth-first search (DFS) or breadth-first search (BFS) algorithms.

  • If during the DFS or BFS traversal, we encounter a back edge or a cycle, then the graph does not have a un...read more

Add your answer

Q145. 4. What is annealing?

Ans.

Annealing is a heat treatment process used to alter the properties of materials, making them more ductile and less brittle.

  • Annealing involves heating a material to a specific temperature and then cooling it slowly.

  • The process relieves internal stresses, improves machinability, and enhances electrical conductivity.

  • Examples of annealing include the heat treatment of steel to reduce hardness and increase toughness, and the annealing of glass to remove internal stresses.

View 1 answer

Q146. Difference between time complexity and space complexity. Explain with example in such a way that you are teaching someone who doesn't know anything about it

Ans.

Time complexity refers to the amount of time taken by an algorithm to run, while space complexity refers to the amount of memory used by an algorithm.

  • Time complexity is measured by the number of operations an algorithm performs, while space complexity is measured by the amount of memory an algorithm uses.

  • An algorithm with a time complexity of O(n) will take longer to run as the input size increases, while an algorithm with a space complexity of O(n) will use more memory as th...read more

Add your answer

Q147. Write down the code for LCA of a binary Tree.

Ans.

Code for finding the Lowest Common Ancestor (LCA) of a binary tree.

  • Start by checking if the root is null or equal to either of the given nodes. If so, return the root.

  • Recursively search for the LCA in the left and right subtrees.

  • If both nodes are found in different subtrees, return the root as the LCA.

  • If both nodes are found in the same subtree, continue searching in that subtree.

View 1 answer
Frequently asked in

Q148. Find minimum path from one city to other city

Ans.

To find minimum path from one city to other city

  • Use Dijkstra's algorithm or A* algorithm to find the shortest path

  • Create a graph with cities as nodes and distances as edges

  • Implement the algorithm in code to get the minimum path

  • Consider factors like traffic, tolls, and road conditions if applicable

Add your answer
Frequently asked in

Q149. Create a program to create all the possible combination using 0 and 1 for n number of digits, for example for n = 2, [00,01, 10,11]

Ans.

Create a program to generate all possible combinations of 0 and 1 for n number of digits.

  • Use a loop to iterate through all possible combinations

  • Use binary representation to generate the combinations

  • Store the combinations in an array of strings

Add your answer
Frequently asked in

Q150. What is the DFT, IPL?

Ans.

DFT stands for Dry Film Thickness and IPL stands for Initial Paint Layer.

  • DFT refers to the thickness of the paint film after it has dried and cured.

  • IPL refers to the first layer of paint applied to a surface.

  • Both DFT and IPL are important factors in ensuring the quality and durability of a paint job.

Add your answer

Q151. What is a master theorem, big o notation?

Ans.

Master theorem and big O notation are used to analyze the time complexity of algorithms.

  • Master theorem is used to solve recurrence relations that arise in the analysis of algorithms.

  • Big O notation is used to describe the upper bound of the growth rate of an algorithm's time complexity.

  • Master theorem can be used to solve the time complexity of divide and conquer algorithms like merge sort and quicksort.

  • Big O notation is commonly used to compare the efficiency of different algo...read more

Add your answer

Q152. Find the output of the given psuedo code and other technical MCQs

Ans.

Psuedo code output and technical MCQs for Software Engineer Intern position

  • Provide examples for technical MCQs

  • Psuedo code output needs to be calculated

  • Assess candidate's technical knowledge

Add your answer

Q153. write a job scheduler code to backup up database daily at a particular time

Ans.

Code to schedule daily database backup

  • Use SQL Server Agent to create a new job

  • Set the schedule to run daily at the desired time

  • Add a step to the job to backup the database

  • Specify the backup location and file name

  • Test the job to ensure it runs successfully

Add your answer

Q154. Program to find the sum of all the digital in the number .

Ans.

Program to find the sum of all the digits in a number.

  • Iterate through each digit in the number and add them together.

  • Convert the number to a string to easily access each digit.

  • Use modulo operator to extract each digit from the number.

  • Handle negative numbers by taking the absolute value before processing.

Add your answer
Frequently asked in

Q155. Check if pair sum exists in the array (Two Sum)?

Ans.

Check if pair sum exists in the array using a hash map.

  • Use a hash map to store the difference between the target sum and each element in the array.

  • Iterate through the array and check if the current element exists in the hash map.

  • Return true if a pair sum exists, otherwise return false.

Add your answer
Frequently asked in

Q156. 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
Frequently asked in

Q157. Find the peak element in the array in O(nlogn) complexity.

Ans.

Use binary search to find peak element in O(nlogn) complexity.

  • Implement binary search to find the peak element in the array.

  • Compare mid element with its neighbors to determine if it is a peak.

  • Divide the array into two halves and recursively search for peak element.

Add your answer
Frequently asked in

Q158. Explain selection sort.

Ans.

Selection sort is a simple sorting algorithm that repeatedly selects the minimum element from an unsorted portion of the array and swaps it with the first unsorted element.

  • Iterate through the array to find the smallest element.

  • Swap the smallest element with the first unsorted element.

  • Repeat the process for the remaining unsorted portion of the array.

  • Time complexity is O(n^2) and space complexity is O(1).

Add your answer

Q159. A point and a rectangle is present with the given coordinates. How will you determine whether the point is inside or outside the rectangle?

Ans.

To determine if a point is inside or outside a rectangle, we check if the point's coordinates fall within the rectangle's boundaries.

  • Check if the point's x-coordinate is greater than the left edge of the rectangle

  • Check if the point's x-coordinate is less than the right edge of the rectangle

  • Check if the point's y-coordinate is greater than the top edge of the rectangle

  • Check if the point's y-coordinate is less than the bottom edge of the rectangle

  • If all four conditions are true...read more

Add your answer

Q160. Number of inversions in an array in O(nlogn) time?

Ans.

Number of inversions in an array in O(nlogn) time.

  • Use merge sort algorithm to count inversions

  • Divide the array into two halves and recursively count inversions

  • Merge the two halves and count split inversions

  • Time complexity is O(nlogn)

Add your answer
Frequently asked in

Q161. Write code- How to compute A^n where n&lt;1 million

Ans.

Compute A^n where n<1 million

  • Use a loop to multiply A by itself n times

  • Optimize the computation by using exponentiation by squaring

  • Handle large numbers by using a big number library or modular arithmetic

Add your answer

Q162. Explain Round Robin Algorithm

Ans.

Round Robin is a CPU scheduling algorithm that assigns a fixed time slice to each process in a circular queue.

  • Each process is given a time slice or quantum to execute.

  • After the time slice is over, the process is preempted and added to the end of the queue.

  • The next process in the queue is then given a time slice to execute.

  • This continues until all processes have executed.

  • The time slice is usually small, typically between 10-100 milliseconds.

  • Round Robin is a preemptive algorith...read more

Add your answer
Frequently asked in

Q163. Describe Radix Sort? ---told

Ans.

Radix Sort is a non-comparative sorting algorithm that sorts data by processing individual digits or characters.

  • Radix Sort is based on the principle of sorting numbers by their digits, from least significant to most significant.

  • It starts by sorting the numbers based on the least significant digit, then moves to the next significant digit, and so on.

  • This process continues until all the digits have been considered, resulting in a sorted array.

  • Radix Sort can be used to sort stri...read more

Add your answer
Frequently asked in

Q164. Write a one line code to find if a given number is a power of 2

Ans.

Check if a number is a power of 2 in one line of code.

  • Use bitwise AND operator to check if the number is greater than 0 and has only one bit set to 1.

  • If the number is a power of 2, it will have only one bit set to 1 in its binary representation.

  • Example: (n & (n-1)) == 0 will return true if n is a power of 2.

Add your answer
Frequently asked in

Q165. Modify Dijkstra algorithm to find 3 Shortest path

Ans.

Modify Dijkstra algorithm to find 3 shortest paths

  • Implement a modified version of Dijkstra's algorithm that keeps track of the 3 shortest paths

  • Use a priority queue to store the nodes and their distances from the source node

  • When a node is visited, update the distances of its neighbors and add them to the priority queue

  • Keep track of the 3 shortest paths using an array or a list

  • Terminate the algorithm when the 3 shortest paths have been found or when the priority queue is empty

Add your answer
Frequently asked in

Q166. β€œCompress a text string in place”. Having seen the famous string expansion in place problem many times, I promptly said run length encoding (i.e. compress aaaaaabbbbbccc to a6b5c3 for example). He asked me to c...

read more
Ans.

Code a run length encoding algorithm to compress a text string in place.

  • Use a loop to iterate through the string and count consecutive characters

  • Create a new string to store the compressed version of the original string

  • Add the character and its count to the new string

  • Compare the length of the new string to the original string to determine if compression was successful

Add your answer

Q167. 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
Frequently asked in

Q168. what is pruning and why it is used

Ans.

Pruning is a technique used in machine learning to reduce the size of a decision tree by removing unnecessary branches.

  • Pruning helps prevent overfitting by simplifying the model.

  • It improves the model's generalization ability by reducing complexity.

  • Pruning can be done through pre-pruning or post-pruning.

  • Pre-pruning involves setting a threshold to stop tree growth early.

  • Post-pruning involves removing branches that do not contribute significantly to accuracy.

  • Example: Removing a ...read more

Add your answer

Q169. Find the sum of two numbers without using any mathematical operarors.

Ans.

Use bitwise operations to find the sum of two numbers without using mathematical operators.

  • Use bitwise XOR to find the sum of two numbers without carrying.

  • Use bitwise AND and left shift to find the carry.

  • Repeat the process until there is no carry left.

Add your answer
Frequently asked in

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

Q171. Find a equilibrium index in array

Ans.

Find an index in array where sum of elements on left side is equal to sum of elements on right side.

  • Loop through array and calculate sum of all elements

  • Then loop through array again and check if sum of elements on left side is equal to sum of elements on right side

  • Return the index if found, else return -1

Add your answer

Q172. write a function to check whether a substring is present in the string

Ans.

A function to check whether a substring is present in a string.

  • Use the built-in string method 'includes()' to check if the substring is present in the string.

  • Return true if the substring is found, otherwise return false.

Add your answer

Q173. If u have a million numbers, how will u find the maximum number from them if β†’ the input is given on the fly i.e. the numbers are entered one by one. β†’ numbers are given 1000 at a time

Ans.

To find the maximum number from a million numbers entered on the fly or 1000 at a time.

  • Create a variable to store the maximum number and initialize it to the first number entered

  • Compare each subsequent number entered with the current maximum and update the variable if necessary

  • If numbers are given 1000 at a time, store the maximum of each batch and compare them at the end to find the overall maximum

View 1 answer
Frequently asked in

Q174. 2. Build a search algorithm for a social media app

Ans.

Build a search algorithm for a social media app

  • Identify relevant search criteria such as keywords, hashtags, user profiles, and location

  • Rank search results based on relevance and popularity

  • Implement filters to refine search results

  • Consider user behavior and search history to personalize results

  • Optimize search speed and efficiency

Add your answer

Q175. Given 8 iron rods of one kg(with one defective rod) find the defective rod with minimum number of weighs

Ans.

Find the defective iron rod among 8 rods of 1kg with minimum number of weighs.

  • Divide the rods into 3 groups of 3, 3, and 2 rods each.

  • Weigh the first two groups against each other.

  • If they balance, the defective rod is in the third group.

  • If they don't balance, the defective rod is in the heavier group.

  • Divide the heavier group into two groups of 1 and 1 or 2 and 2 rods each.

  • Weigh the two rods against each other.

  • If they balance, the defective rod is the remaining one.

  • If they don'...read more

View 1 answer
Frequently asked in

Q176. Given a string INPUT, find the longest repeating substring

Ans.

Find the longest repeating substring in a given string.

  • Create an array of all possible substrings of the given string.

  • Sort the array in lexicographic order.

  • Find the longest common prefix between adjacent strings.

  • Return the longest common prefix found.

  • If no repeating substring is found, return an empty string.

Add your answer

Q177. How will you implement a shuffle function for a playlist of songs

Ans.

Implementing a shuffle function for a playlist of songs

  • Create a new empty playlist

  • Randomly select a song from the original playlist and add it to the new playlist

  • Remove the selected song from the original playlist

  • Repeat until all songs have been added to the new playlist

  • Return the new shuffled playlist

Add your answer

Q178. How will you print all the subsets of a given set?

Ans.

Printing all subsets of a given set.

  • Use recursion to generate all possible subsets.

  • For each element in the set, either include it or exclude it in the subset.

  • Base case is when the set is empty, print the subset.

  • Time complexity is O(2^n) where n is the size of the set.

Add your answer
Frequently asked in

Q179. Write pseudocode for linear search

Ans.

Pseudocode for linear search algorithm on an array of strings

  • Initialize a variable to store the search key

  • Iterate through each element in the array

  • Compare each element with the search key

  • Return the index if found, otherwise return -1

Add your answer

Q180. Find the kth smallest value in an unsorted array

Ans.

Find the kth smallest value in an unsorted array

  • Sort the array and return the kth element

  • Use quickselect algorithm to find the kth smallest element in O(n) time

  • Build a min heap of size k and traverse the array to find the kth smallest element

Add your answer

Q181. Count the number of subarrays in a given array whose sum is divisible by k.

Ans.

Count subarrays in an array whose sum is divisible by k.

  • Create a prefix sum array to keep track of the sum of elements up to a certain index.

  • Use a hash table to store the frequency of remainders when the prefix sum is divided by k.

  • For each prefix sum, check if there exists a previous prefix sum with the same remainder.

  • If yes, add the frequency of that remainder to the count of subarrays.

  • Update the frequency of the current remainder in the hash table.

  • Return the count of subarr...read more

Add your answer

Q182. Find maximum element in an array in less dhan O(N)

Ans.

Find maximum element in an array in less than O(N)

  • Use divide and conquer approach

  • Compare maximum of left and right subarrays

  • Recursively find maximum element

Add your answer

Q183. Convert Roman numeral to decimal number.

Ans.

Convert Roman numeral to decimal number

  • Create a dictionary mapping each Roman numeral to its corresponding decimal value

  • Iterate through the Roman numeral from left to right

  • If the current numeral is smaller than the next numeral, subtract its value from the total

  • Otherwise, add its value to the total

Add your answer

Q184. Find longest substring

Ans.

Find the longest substring in an array of strings.

  • Iterate through each string and compare with all other strings to find common substrings.

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

  • Return the substring with the highest frequency.

Add your answer
Frequently asked in

Q185. find the two no from array that lead to particular sum

Ans.

Finding two numbers from an array that add up to a specific sum.

  • Loop through the array and for each element, check if the difference between the sum and the element exists in the array.

  • If it does, return the two numbers.

  • If it doesn't, continue looping until all elements have been checked.

Add your answer

Q186. Find mean of the given array

Ans.

To find the mean of an array, add all the elements and divide by the number of elements.

  • Add all the elements of the array

  • Divide the sum by the number of elements

  • Return the mean value

Add your answer

Q187. how to reverse the link list? find all possible sub sequences in a given array

Ans.

Reverse a linked list and find all possible subsequences in a given array.

  • To reverse a linked list, iterate through the list and change the next pointers of each node to the previous node.

  • To find all possible subsequences in an array, use recursion and generate all possible combinations of elements.

  • For example, given the array [1, 2, 3], the possible subsequences are [], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3].

View 1 answer
Frequently asked in
Q188. Count Number Of Ones

Ninja has an integer β€˜N’. Ninja is fond of digit β€˜1’ so Ninja wants to know the number of 1s in each number from 0 to N.

Your task is to help the Ninja in finding out the number of ones from...read more

Ans.

The task is to count the number of occurrences of the digit '1' in each number from 0 to N.

  • Iterate through each number from 0 to N

  • Convert each number to a string

  • Count the number of occurrences of the digit '1' in the string representation of each number

  • Return the total count of '1's

View 2 more answers

Q189. Find the non overlapping intervals

Ans.

Given a list of intervals, find the non-overlapping intervals.

  • Sort the intervals based on their start time.

  • Iterate through the intervals and keep track of the latest end time.

  • If the start time of the current interval is greater than the latest end time, add it to the non-overlapping intervals.

  • If the start time of the current interval is less than or equal to the latest end time, skip it as it overlaps with the previous interval.

Add your answer
Q190. Maximum sum of two non-overlapping subarrays of a given size

You are given an array/list ARR of integers and a positive integer β€˜K’. Your task is to find two non-overlapping subarrays (contiguous) each of length...read more

Ans.

The task is to find two non-overlapping subarrays of length K in an array, such that their sum is maximum.

  • Iterate through the array and calculate the sum of each subarray of length K

  • Store the maximum sum obtained from the first subarray

  • Iterate again and calculate the sum of each subarray of length K, excluding the previous subarray

  • Store the maximum sum obtained from the second subarray

  • Return the sum of the two maximum sums

View 2 more answers

Q191. Write a code, find out the unique element from an array?

Ans.

Code to find unique element from an array

  • Loop through array and compare each element with rest of the array

  • If element is not repeated, add it to a new array

  • Return the new array with unique elements

Add your answer

Q192. Calculate second max without second loop and sorting

Ans.

Find the second maximum value in an array without using a second loop or sorting.

  • Iterate through the array once, keeping track of the maximum and second maximum values.

  • Initialize the maximum and second maximum variables with the first and second elements of the array.

  • Compare each element with the maximum and second maximum variables, updating them if necessary.

  • At the end of the iteration, the second maximum variable will hold the second largest value.

View 2 more answers

Q193. find the lca of a given nodes

Ans.

The lowest common ancestor (LCA) of two nodes in a tree is the shared ancestor that is located farthest from the root.

  • Traverse the tree from the root to find the paths from the root to each node.

  • Compare the paths to find the last common node between the two paths, which is the LCA.

  • If one node is an ancestor of the other, return that node as the LCA.

Add your answer
Frequently asked in

Q194. Write function to calculate value of x to the power of n

Ans.

Function to calculate x to the power of n

  • Create a function that takes two parameters, x and n

  • Use a loop to multiply x by itself n times

  • Return the result

Add your answer
Frequently asked in

Q195. How to serve problem

Ans.

To serve a problem in Sales & Marketing, one must understand the customer's needs and provide tailored solutions.

  • Listen actively to the customer's concerns and requirements

  • Identify the root cause of the problem

  • Offer personalized solutions that address the customer's specific pain points

  • Provide excellent customer service and support throughout the process

  • Continuously evaluate and improve the offered solutions based on customer feedback

View 1 answer

Q196. Explain the program shown? How it works?

Ans.

The program is a software application that performs a specific task or set of tasks.

  • The program is written in a specific programming language.

  • It may have a user interface or operate in the background.

  • It takes input data, processes it, and produces output.

  • It may use algorithms, data structures, and external libraries.

  • Examples: a calculator program, a file compression program, a web browser.

View 1 answer

Q197. Reduce the process time and call back to early

Ans.

To reduce process time and call back early, we need to analyze the current process and identify bottlenecks.

  • Analyze the current process flow

  • Identify bottlenecks and areas of improvement

  • Implement process improvements such as automation or streamlining

  • Monitor and measure the impact of changes

  • Continuously review and improve the process

View 1 answer
Frequently asked in

Q198. How you would teach algorithm to students?

Ans.

I would teach algorithms to students by providing clear explanations, practical examples, and hands-on coding exercises.

  • Start by explaining the basic concepts of algorithms, such as input, output, and steps.

  • Provide real-life examples to help students understand the relevance and applications of algorithms.

  • Break down complex algorithms into smaller, more manageable steps.

  • Encourage students to actively participate in the learning process through coding exercises and problem-sol...read more

View 1 answer

Q199. What is a algorithm

Ans.

An algorithm is a step-by-step procedure or set of rules for solving a problem or accomplishing a task.

  • An algorithm is a well-defined computational procedure.

  • It consists of a sequence of instructions that are executed in a specific order.

  • Algorithms can be represented using flowcharts, pseudocode, or programming languages.

  • They are used in various fields, including mathematics, computer science, and finance.

  • Examples of algorithms include sorting algorithms (e.g., bubble sort, m...read more

View 1 answer

Q200. Find best time to buy and sell stock

Ans.

The best time to buy and sell stock can be found by identifying the lowest valley and highest peak in the stock prices.

  • Identify the lowest valley and highest peak in the stock prices

  • Calculate the difference between the two

  • Repeat the process for different time periods to find the maximum profit

  • Consider edge cases where there is no profit to be made

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

Interview experiences of popular companies

3.7
Β β€’Β 10.4k Interviews
3.6
Β β€’Β 7.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
4.0
Β β€’Β 555 Interviews
3.5
Β β€’Β 376 Interviews
3.9
Β β€’Β 233 Interviews
View all
Algorithms Interview Questions
Share an Interview
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
70 Lakh+

Reviews

5 Lakh+

Interviews

4 Crore+

Salaries

1 Cr+

Users/Month

Contribute to help millions

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

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