Top 250 Algorithms Interview Questions and Answers
Updated 21 Jan 2025
Q201. What is the logic behind your code?
The logic behind my code is to efficiently solve the given problem using algorithms and data structures.
I analyze the problem requirements and constraints.
I break down the problem into smaller subproblems.
I choose appropriate algorithms and data structures.
I implement the code using clean and readable syntax.
I test and debug the code to ensure correctness and efficiency.
Q202. How fo use delete duplicate
Delete duplicate is a function to remove duplicate entries from a list or array.
Identify the duplicate entries in the list or array
Use a loop to iterate through the list or array
Remove the duplicate entries using the 'delete' keyword or a built-in function
Ensure that the remaining entries are still in the correct order
Q203. Explain one algo ,OOPS concept
OOPS concept - Inheritance
Inheritance is a mechanism in OOPS where a new class is derived from an existing class
The new class inherits all the properties and behavior of the existing class
It allows code reusability and helps in creating a hierarchy of classes
Example: A class 'Car' can be inherited by a class 'SUV' which will have all the properties of 'Car' and additional properties specific to 'SUV'
Inheritance can be of different types - single, multiple, multilevel, hierarc...read more
Q204. Predict the winner leetcode problem
The winner leetcode problem involves finding the candidate with the most votes in an election scenario.
Iterate through the list of candidates and keep track of their votes
Return the candidate with the highest number of votes
Example: Input - ['Alice', 'Bob', 'Alice', 'Charlie', 'Bob'], Output - 'Alice'
Q205. 2.what is fully developed flow can you explain in depth with math?
Fully developed flow is a state where the velocity profile of a fluid remains constant over time and distance.
Fully developed flow occurs in long pipes where the fluid has enough time to reach a steady state.
In this state, the velocity profile is parabolic and the flow is laminar.
The Reynolds number is used to determine if the flow is fully developed or not.
Mathematically, fully developed flow is described by the Hagen-Poiseuille equation.
The Hagen-Poiseuille equation relates...read more
Q206. Coding question 1. Find maximum subarray
Maximum subarray problem is to find the contiguous subarray with maximum sum in an array of integers.
Use Kadane's algorithm to find the maximum subarray sum in linear time complexity.
Initialize two variables, max_so_far and max_ending_here, to track the maximum sum so far and the maximum sum ending at the current index, respectively.
Iterate through the array and update max_ending_here and max_so_far accordingly.
Return max_so_far as the maximum subarray sum.
Q207. Find first minimum and maximum number in an array using streams
Find first minimum and maximum number in an array using streams
Use IntStream to convert array to stream of integers
Use min() and max() methods to find minimum and maximum values
Use findFirst() method to get the first occurrence of minimum and maximum values
Q208. 1.Find the possible permutation of the given string 2. Remove 3 from the given input (Number) and input should be taken from the user 3. Check whether the given string is Anagram without using map DATA structur...
read moreAnswering questions related to string permutations, removing numbers, and checking for anagrams without using map data structure.
To find permutations of a string, use recursion to swap characters at each position.
To remove a specific character (e.g. '3') from a string, iterate through the string and build a new string without the character.
To check for anagrams without using a map data structure, sort both strings and compare character by character.
Algorithms Jobs
Q209. What is RPN and how to calculate RPN?
RPN stands for Risk Priority Number and is used to prioritize risks based on severity, occurrence, and detection.
RPN is calculated by multiplying the severity, occurrence, and detection scores of a risk.
The severity, occurrence, and detection scores are typically rated on a scale of 1-10.
The higher the RPN, the higher the priority of the risk.
RPN can be used to prioritize which risks to address first.
Example: A risk with a severity score of 8, occurrence score of 5, and detec...read more
Q210. How many parameters mantain?
As a CCR Operator, I maintain multiple parameters depending on the plant and equipment.
The number of parameters varies depending on the plant and equipment being operated.
Some common parameters include temperature, pressure, flow rate, and chemical levels.
It is important to monitor and adjust these parameters to ensure safe and efficient operation.
Regular maintenance and calibration of equipment is necessary to ensure accurate readings.
Proper documentation of parameter readin...read more
Q211. Rotate an image in your choice of language
To rotate an image in Python, use the Pillow library's rotate() method.
Import the Image module from the Pillow library
Open the image using the open() method
Use the rotate() method to rotate the image by the desired angle
Save the rotated image using the save() method
Q212. Explain Greedy algorithms and Divide and Conquer techniques
Greedy algorithms make the optimal choice at each step, while Divide and Conquer breaks a problem into smaller subproblems.
Greedy algorithms select the best option at each step without considering the overall solution
Divide and Conquer divides a problem into smaller subproblems, solves them recursively, and then combines the solutions
Example of Greedy algorithm: Dijkstra's shortest path algorithm
Example of Divide and Conquer: Merge Sort
Q213. sort a right and left side of array except middle element
Sort the left and right side of an array except the middle element.
Split the array into left and right sides based on the middle element.
Sort the left and right sides separately.
Combine the sorted left and right sides with the middle element in between.
Q214. Print * using loops
Printing * using loops is a basic programming exercise.
Use nested loops to print * in a pattern
Use a for loop to print * in a straight line
Use a while loop to print * until a certain condition is met
Q215. How to find the largest number in the given array?
To find the largest number in an array, loop through the array and compare each element with a variable holding the current largest number.
Initialize a variable with the first element of the array
Loop through the array and compare each element with the variable holding the current largest number
If the current element is larger than the variable, update the variable with the current element
After the loop, the variable will hold the largest number in the array
Q216. what is backtracking
Backtracking is a technique used to solve problems by trying out different solutions and undoing them if they fail.
It is a trial-and-error approach to problem-solving
It involves trying out different solutions and undoing them if they fail
It is often used in algorithms for searching and optimization problems
Examples include solving Sudoku puzzles and finding the shortest path in a maze
Q217. If swiggy had a new user and we have no information about him other than his phone number, how will you recommend restaurants to him?
I would recommend restaurants based on the user's location, cuisine preferences, and popular restaurants in the area.
Use the user's phone number to determine their location
Ask the user for their cuisine preferences during the onboarding process
Recommend popular restaurants in the area based on user reviews and ratings
Use machine learning algorithms to personalize recommendations based on user behavior
Q218. What's is effective depth?
Effective depth is the distance from the centroid of the tension reinforcement to the extreme compression fiber.
It is a measure of the strength of a reinforced concrete beam or slab.
It is calculated by subtracting the cover from the overall depth of the section.
It is used to determine the amount of reinforcement required for a given load.
For example, if the overall depth of a beam is 500mm and the cover is 50mm, the effective depth would be 450mm.
Q219. write code for Anagram program
An Anagram program compares two strings to see if they are rearrangements of each other.
Create a function that takes in two strings as input
Remove any spaces and convert both strings to lowercase for accurate comparison
Sort the characters in both strings and compare them to check if they are anagrams
Return true if they are anagrams, false otherwise
Q220. Optimize the given program from O(n2) to O(log n)
Optimize O(n2) program to O(log n)
Use binary search instead of linear search
Divide and conquer approach can be used
Implement efficient data structures like heap, AVL tree, etc.
Reduce unnecessary iterations and comparisons
Use memoization to avoid redundant calculations
Q221. How to make partition
To make a partition, you need to use a disk management tool or command prompt.
Open Disk Management tool or Command Prompt
Select the disk you want to partition
Right-click on the unallocated space and select 'New Simple Volume'
Follow the wizard to specify the size and format of the partition
Alternatively, use the 'diskpart' command in Command Prompt to create a partition
Q222. Find peak in increasing and decreasing sequence
Find peak in increasing and decreasing sequence
Use binary search to find the peak element
Compare the middle element with its neighbors to determine if it's a peak
If the middle element is smaller than its left neighbor, search in the left half of the array
If the middle element is smaller than its right neighbor, search in the right half of the array
Q223. write a code for lcm and hcf
Code to find LCM and HCF of two numbers
Use Euclidean algorithm to find HCF
LCM = (num1 * num2) / HCF
Handle edge cases like zero or negative numbers
Q224. Find all the pairs present in an array
The question asks to find all the pairs present in an array of strings.
Iterate through the array and compare each element with all other elements to find pairs.
Store the pairs in a separate array or data structure.
Consider the order of elements in pairs, i.e., (A, B) is different from (B, A).
Q225. Write a program swapping of two numbers without using third variable
Swapping two numbers without using a third variable in a program
Use bitwise XOR operation to swap two numbers without using a third variable
Example: int a = 5, b = 10; a = a ^ b; b = a ^ b; a = a ^ b; // Now a = 10, b = 5
Ensure the numbers are not the same to avoid getting 0 as a result
Q226. Write a code to find maximum in an array?
Code to find maximum in an array of strings
Iterate through the array and compare each element to find the maximum
Use a variable to store the current maximum value and update it as needed
Consider converting string elements to numbers if necessary for comparison
Q227. in range of [1-40] kgs, select minimum number of weight to cover the complete range of weights.
To cover the range of weights from 1-40 kgs, select weights in powers of 2.
Select weights in powers of 2: 1, 2, 4, 8, 16, 32
These weights can cover the complete range from 1-40 kgs
Example: 1 kg + 2 kg + 4 kg + 8 kg + 16 kg + 32 kg = 63 kgs
Q228. Design a search engine and metrics to measure it's success
Designing a search engine and measuring its success involves understanding user needs and behavior, optimizing search algorithms, and tracking key metrics.
Identify user needs and behavior through user research and data analysis
Optimize search algorithms to provide relevant and accurate results
Track key metrics such as click-through rate, bounce rate, and conversion rate
Continuously iterate and improve the search engine based on user feedback and data analysis
Ensure the search...read more
Q229. find the longest substring in string without repeating characters
Find the longest substring in a string without repeating characters.
Use a sliding window approach to iterate through the string.
Keep track of the characters seen so far in a set.
Update the start of the window when a repeating character is encountered.
Calculate the length of the current substring and update the longest substring found.
Repeat until the end of the string is reached.
Q230. What is the LSCS
LSCS stands for Lower Segment Cesarean Section, a surgical procedure to deliver a baby through an incision in the mother's abdomen and uterus.
LSCS is commonly performed when a vaginal delivery is not possible or safe for the mother or baby.
It is also known as C-section.
The incision is usually made in the lower part of the abdomen, below the bikini line.
LSCS may be planned (elective) or done as an emergency procedure.
After the baby is delivered, the incision is closed with sti...read more
Q231. Write even and odd number code
Code to print even and odd numbers
Use a loop to iterate through numbers
Check if the number is even or odd using modulus operator
Print the number accordingly
Q232. Difference between BF and PAL
BF and PAL are both types of eyeglass lenses used to correct vision, but they have different designs and purposes.
BF stands for Bifocal lenses, which have two distinct areas for near and distance vision.
PAL stands for Progressive Addition Lenses, which have a gradual transition of power for different distances.
BF lenses have a visible line separating the two areas, while PAL lenses have a seamless design.
BF lenses are typically used for presbyopia, while PAL lenses are used f...read more
Q233. Find in rotated sorted array
Search for a target value in a rotated sorted array.
Use binary search to find the pivot point where the array is rotated.
Determine which half of the array the target value lies in based on the pivot point.
Continue binary search in the appropriate half of the array to find the target value.
Q234. find even number from the array
Use a loop to iterate through the array and check if each element is an even number.
Iterate through the array using a loop
Check if each element is divisible by 2 without a remainder
Store the even numbers in a separate array or print them out
Q235. Convert roman to int number
Convert roman to int number
Create a dictionary of roman numerals and their integer values
Iterate through the roman numeral string and add corresponding integer values
Subtract twice the value of previous numeral if it is smaller than current numeral
Q236. find the frequecy of string in a large paragraph
The question asks to find the frequency of a specific string in a large paragraph.
Use a loop to iterate through each word in the paragraph
Compare each word with the given string
Keep a count of the number of times the string appears
Q237. Given an undirected graph, if dist(u,v)>n/2. Show that there exists a vertex x such that removing x makes u and v go to different connected components.
If dist(u,v)>n/2 in an undirected graph, there exists a vertex x such that removing x makes u and v go to different connected components.
Find the shortest path between u and v
If the path length is greater than n/2, then there must be a vertex x on the path
Removing x will separate u and v into different connected components
Q238. Finding largest sub set in a list
Find the largest sub set in a list of strings
Iterate through the list of strings and keep track of the length of each subset
Compare the lengths of subsets to find the largest one
Return the largest subset
Q239. Show that for a grid of size n*n, if n is odd then there cannot be a Hamiltonian cycle in the graph
For an odd-sized grid, there cannot be a Hamiltonian cycle in the graph.
A Hamiltonian cycle is a path that visits every vertex exactly once and ends at the starting vertex.
In an n*n grid, there are n^2 vertices and each vertex has degree 4.
For an odd n, the total degree of all vertices is odd, which means there cannot be a Hamiltonian cycle.
Q240. Find number of Island in given binary matrix
Count the number of islands in a binary matrix.
Traverse the matrix and for each 1 encountered, perform DFS to mark all connected 1s as visited.
Increment the island count for each new DFS traversal.
Use a visited matrix to keep track of visited cells.
Consider diagonal cells as connected if required.
Optimize by using Union-Find data structure.
Q241. Swap the value of two variables without using the third variable
To swap the value of two variables without using a third variable, use arithmetic operations.
Use addition and subtraction to swap values
Example: a = 5, b = 10. a = a + b (a = 15), b = a - b (b = 5), a = a - b (a = 10)
Q242. An array contain 6 different numbers, only 1 number is repeated for 5 times. So now total 10 numbers in array, Find that duplicate number in 2 steps only?
Find the duplicate number in an array of 10 numbers with only 2 steps.
Use a hash set to keep track of visited numbers.
Iterate through the array and check if the number is already in the set.
If it is, then it is the duplicate number.
If not, add it to the set.
At the end, the duplicate number will be found.
Q243. Write a program for sum of numbers?
A program to calculate the sum of numbers.
Create a variable to store the sum.
Iterate through the numbers and add each number to the sum.
Return the sum.
Q244. Given a chessboard find maximum number of squares present
Given a chessboard, find the maximum number of squares present.
Start with the smallest square and count all possible squares
Use the formula n*(n+1)*(2n+1)/6 to find the total number of squares in an n x n chessboard
Add up the squares of all sizes from 1 to n to get the maximum number of squares
For example, an 8 x 8 chessboard has 204 squares
Q245. Given a 8X8 chessboard write a condition such that if 2 queens on the chessboard kill each other then return True else Return False
Check if two queens on a chessboard can kill each other
Iterate through each queen's position and check if they are in the same row, column, or diagonal
If any two queens are in the same row, column, or diagonal, return True
Otherwise, return False
Q246. there is array of n numbers & u hv to find sum(=0) of m numbers
Given an array of numbers, find a subset of numbers whose sum is zero.
Use a combination of numbers from the array to find subsets whose sum is zero.
Iterate through all possible combinations of numbers and check if their sum is zero.
Consider using recursion or backtracking to generate all possible combinations.
Optimize the solution by using memoization or dynamic programming to avoid redundant calculations.
Q247. Explain bosting?
Boosting is an ensemble learning technique that combines multiple weak models to create a strong model.
Boosting iteratively trains weak models on different subsets of data
Each subsequent model focuses on the misclassified data points of the previous model
Final prediction is made by weighted combination of all models
Examples include AdaBoost, Gradient Boosting, XGBoost
Q248. what is a worst case analysis
Worst case analysis is a method used to determine the maximum possible performance or behavior of a system under extreme conditions.
Worst case analysis involves identifying the most unfavorable conditions that a system may encounter.
It helps in ensuring that the system will still function correctly even under the worst possible circumstances.
This analysis is important for designing reliable systems that can handle extreme scenarios.
For example, in hardware design, worst case ...read more
Q249. Coding on Content providersGiven a rotated array ‘K’ times (K unknown), find a number in most efficient way
Given a rotated array, find a number efficiently.
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 case when the target number is at the pivot point.
Q250. List down all the parameters you’d evaluate to design the restaurant recommendation algorithm for Swiggy.
Parameters for designing restaurant recommendation algorithm for Swiggy
User's location and distance from the restaurant
User's previous orders and ratings
Restaurant's popularity and ratings
Cuisine type and availability
Time of day and day of the week
Special offers and discounts
Delivery time and availability
User's dietary preferences and restrictions
Top Interview Questions for Related Skills
Interview Questions of Algorithms Related Designations
Interview experiences of popular companies
Reviews
Interviews
Salaries
Users/Month