Find Interview Questions for Top Companies
Ques:- How Many Algorithms You Can Do Perfectly ?
Asked In :-
Right Answer:
The number of algorithms I can do perfectly depends on my experience and practice, but I can confidently handle a wide range of common algorithms, including sorting, searching, dynamic programming, and graph algorithms.
Ques:- A non-empty zero-indexed array A consisting of N integers is given. The first covering prefix of array A is the smallest integer P such that $0 leq P < N$ and such that every value that occurs in array A also occurs in sequence $A[0], A[1], l...
Asked In :- cern,
Right Answer:
To find the first covering prefix of the array A, iterate through the array while maintaining a set of the unique elements encountered. The first index P where the size of this set equals the total number of unique elements in A is the first covering prefix. Return P.
Ques:- Given two Arrays {a1,a2,a3,.ai…aj…an} {b1,b2,b3,…bi…bj…bn). Note the size of both arrays are same.. We have to arrange the arrays in such a way such that aibi > ajbj. and ai > bi and aj > bj.
Right Answer:
To arrange the arrays such that ( a_i b_i > a_j b_j ) and ( a_i > b_i ) and ( a_j > b_j ), sort both arrays in descending order. Then, pair the elements from both arrays in the same order. This will ensure that the conditions are satisfied.
Ques:- Quick-sort is run on two inputs shown below to sort in ascending order (i) 1,2,3, .,n (ii) n, n – 1, n – 2, ., 2, 1 Let C1 and C2 be the number of comparisons made for the inputs (i) and (ii) respectively. Then,
Asked In :- Zoox, lam research,
Right Answer:
C1 < C2
Ques:- What are NP complete and NP hard problems?
Asked In :-
Right Answer:
NP-complete problems are a subset of NP problems that are as hard as the hardest problems in NP, meaning if you can solve one NP-complete problem quickly, you can solve all NP problems quickly. NP-hard problems are at least as hard as NP-complete problems but are not necessarily in NP; they may not have solutions that can be verified quickly.
Ques:- Vankin’s Mile is played on an n×n grid. Starting at any cell, you can move only right or down, collecting the value at each cell. The goal is to reach the bottom-right cell with the maximum total score. How do you solve this?
Asked In :-
Right Answer:

Use Dynamic Programming to compute the maximum score from each cell.

✅ Python Solution (Top-down with memoization):

def max_score(grid):
n = len(grid)
dp = [[-1]*n for _ in range(n)]

def dfs(i, j):
if i >= n or j >= n:
Comments
DK BOSS Jul 30, 2021

Vankin’s Mile is an American solitaire game played on an n ? n square grid. The
player starts by placing a token on any square of the grid. Then on each turn, the player moves
the token either one square to the right or one square down. The game ends when player moves
the token o the edge of the board. Each square of the grid has a numerical value, which could be
positive, negative, or zero. The player starts with a score of zero; whenever the token lands on a
square, the player adds its value to his score. The object of the game is to score as many points
as possible. For example, given the grid below, the player can score 8 − 6 + 7 − 3 + 4 = 10 points
by placing the initial token on the in the second row, and then moving down, down, right, down,
down. (This is not the best possible score for this grid of numbers.)
(a) Describe and analyze an ecient algorithm to compute the maximum possible score for a game
of Vankin’s Mile, given the n × n array of values as input.
(b) In the European version of this game, appropriately called Vankin?s Kilometer, the player
can move the token either one square down, one square right, or one square left in each turn.
However, to prevent infinite scores, the token cannot land on the same square more than
once. Describe and analyze an ecient algorithm to compute the maximum possible score for
a game of Vankin’s Kilometer, given the n × n array of values as input.

Ques:- Given an array of 2n elements of which n elements are same and the remaining n elements are all different. Write a C program to find out the value which is present n times in the array
Asked In :- maxar technologies,
Right Answer:
```c
#include <stdio.h>

int findRepeatedElement(int arr[], int size) {
int count[size];
for (int i = 0; i < size; i++) {
count[i] = 0;
}

for (int i = 0; i < size; i++) {
count[arr[i]]++;
if (count[arr[i]] == size / 2) {
return arr[i];
}
}
return -1; // In case no element is found
}

int main() {
int arr[] = {1, 2, 3, 2, 2, 4, 5, 2}; // Example input
int n = sizeof(arr) / sizeof(arr[0]);
int result = findRepeatedElement(arr, n);
printf("The element that appears n times is: %dn", result);
return 0;
}
```
Ques:- Test cases for vending machine
Asked In :-
Right Answer:
1. **Valid Coin Insertion**: Insert a valid coin and check if the machine accepts it and updates the balance correctly.

2. **Invalid Coin Insertion**: Insert an invalid coin and verify that the machine does not accept it and returns the coin.

3. **Product Selection**: Select a product after sufficient balance is available and ensure the product is dispensed correctly.

4. **Insufficient Balance**: Attempt to select a product without enough balance and check if the machine prompts for more coins.

5. **Exact Change**: Insert the exact amount for a product and confirm that the product is dispensed and the balance is zero.

6. **Change Dispensing**: Insert more than the required amount for a product and verify that the correct change is returned.

7. **Empty Product Slot**: Attempt to select a product that is out of stock and ensure the machine notifies the user.

8. **Cancel Transaction**: Request to cancel the transaction and check if the
Ques:- Given an expression get rid of the pointless brackets in it with out making an ambiguity in its execution. input output ex1: (a+(b)+c) a+b+c
Asked In :- ntp,
Right Answer:
To remove pointless brackets from the expression `(a+(b)+c)`, you can simplify it to `a+b+c`.
Ques:- Print prime factors of an integer and count of each of those.
Right Answer:
To print the prime factors of an integer and their counts, you can use the following Python code:

```python
def prime_factors(n):
factors = {}
# Check for number of 2s that divide n
while n % 2 == 0:
if 2 in factors:
factors[2] += 1
else:
factors[2] = 1
n //= 2

# n must be odd at this point, check for odd factors
for i in range(3, int(n**0.5) + 1, 2):
while n % i == 0:
if i in factors:
factors[i] += 1
else:
factors[i] = 1
n //= i

# This condition is to check if n is a prime number greater than 2
if n > 2:
factors[n] = 1
Ques:- How do you reverse the words in a sentence like “have a nice day” to become “day nice a have”?
Asked In :- epra,
Right Answer:

def reverse_words(sentence):
words = sentence.strip().split()
return ‘ ‘.join(reversed(words))

Explanation:

s = “have a nice day”
print(reverse_words(s)) # Output: “day nice a have”

✅ C Version:

#include <stdio.h>
#include <string.h>

void reverse_words(char* str) {
char* words[100];
int count = 0;

cpp
char* token = strtok(str, " ");
while (token != NULL) {
words[count++] = token;
token = strtok(NULL, " ");
}

for (int i = count - 1; i >= 0; i--) {
printf("%s", words[i]);
if (i > 0) printf(" ");
}
printf("\n");

}

int main() {
char sentence[] = “have a nice day”;
reverse_words(sentence);
return 0;
}

✅ Output:
day nice a have

Comments
abhishekh dubey Aug 24, 2022

str='Have a nice day'
new_str=str.split(' ');
final_str=[]
for(let i = new_str.length-1;i>=0; i--){
final_str.push(new_str[i])
// console.log(i );
}
console.log(final_str.join(' '));

Gowri Krishnan Aug 14, 2022

$str = explode(" ","have a nice day");
$array_rev = array_reverse($str);
echo implode(" ",$array_rev);

GUGULOTH AJAY KUMAR Mar 9, 2022

str = "have a nice day".split()
new_str = ""
for word in str:
new_str = word+ " " +new_str
print(new_str)

Ques:- Given a fair coin, make an unfair coin that head with p probability and tail with (1-p) probability where 0 < p < 1.
Asked In :-
Right Answer:
To create an unfair coin that lands heads with probability ( p ) and tails with probability ( 1-p ), you can use the following method:

1. Flip the fair coin twice.
2. Define the outcomes as follows:
- If the first flip is heads (H) and the second flip is heads (H), return heads (H).
- If the first flip is heads (H) and the second flip is tails (T), return heads (H) with probability ( p ) and tails (T) with probability ( 1-p ).
- If the first flip is tails (T), return tails (T).

This way, you can achieve the desired probabilities for heads and tails.
Ques:- You have millions of lines of data. 2 lines are identical, the rest are unique. Some lines are so long, that they do not fit in memory. How would you find those 2 identical lines?
Asked In :-
Right Answer:
Use a hash function to create a hash for each line of data. Store these hashes in a set. As you process each line, check if its hash already exists in the set. If it does, you've found the duplicate line. If not, add the hash to the set. For lines that don't fit in memory, process them in chunks or use external sorting techniques to handle them efficiently.
Ques:- Write a code for minimal spanning tree
Asked In :-
Right Answer:
```python
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = []

def add_edge(self, u, v, w):
self.graph.append((w, u, v))

def find(self, parent, i):
if parent[i] == i:
return i
return self.find(parent, parent[i])

def union(self, parent, rank, x, y):
xroot = self.find(parent, x)
yroot = self.find(parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1

def kruskal(self):
result = []
self.graph.sort()
parent = []
rank = []
for node
Ques:- Suppose you are given an infinite series of strings, each at a certain position as follows: 1. a 2. b 3. c 4. d .. 26.z 27.aa 28.ab .. 52.az
Asked In :-
Right Answer:
To find the string at a given position ( n ), use the following approach:

1. Decrement ( n ) by 1 to convert it to a zero-based index.
2. Initialize an empty string for the result.
3. While ( n ) is greater than or equal to 0:
- Calculate the remainder ( r ) as ( n mod 26 ).
- Prepend the character corresponding to ( r + 97 ) (ASCII value for 'a' is 97) to the result.
- Update ( n ) to ( n // 26 - 1 ).
4. Return the result.

For example, for position 28, the result would be "ab".
Ques:- Given an array A[] and a integer K. Find the combination of four no's in the array whose sum is equal to K.
Asked In :- vmware airwatch, novatech,
Right Answer:
To find the combination of four numbers in the array A[] whose sum equals K, you can use the following approach:

1. Sort the array A[].
2. Use four nested loops to iterate through the array, but optimize by skipping duplicates and using two pointers for the innermost loop.
3. For each combination of the first two numbers, use two pointers to find the other two numbers that complete the sum to K.

Here’s a sample code in Python:

```python
def four_sum(A, K):
A.sort()
result = []
n = len(A)

for i in range(n - 3):
if i > 0 and A[i] == A[i - 1]:
continue
for j in range(i + 1, n - 2):
if j > i + 1 and A[j] == A[j - 1]:
continue
left, right = j + 1, n -
Ques:- Which is of the sorting algos is memory inefficient? Quick, merge, bubble.
Asked In :-
Right Answer:
Bubble sort is memory inefficient.
Ques:- Given an array of numbers : a1, a2, a3….. an…. (a) divide them in such a way that every alternate segment is given to two persons john and mary, equally,null,,null, the number of segments made should be minimum… eg….<br ...>
Asked In :-
Right Answer:
To divide the array into segments for John and Mary, alternate segments should be assigned to each person. The minimum number of segments can be achieved by dividing the array into two equal parts if the length is even, or into two parts where one part has one more element if the length is odd.

For example:
- If the array has 6 elements: [a1, a2, a3, a4, a5, a6], the segments would be:
- John: [a1, a2, a3]
- Mary: [a4, a5, a6]

- If the array has 5 elements: [a1, a2, a3, a4, a5], the segments would be:
- John: [a1, a2, a3]
- Mary: [a4, a5]

Thus, the segments are assigned alternately, and the number of segments is minimized.
Ques:- Imagine a (literal) stack of plates. If the stack gets too high, it might topple. Therefore, in real life, we would likely start a new stack when the previous stack exceeds some threshold. Implement a data structure SetOfStacks that mimics t…
Asked In :- De Shaw, energy exemplar,
Right Answer:
```python
class SetOfStacks:
def __init__(self, threshold):
self.threshold = threshold
self.stacks = []

def push(self, value):
if not self.stacks or len(self.stacks[-1]) >= self.threshold:
self.stacks.append([])
self.stacks[-1].append(value)

def pop(self):
if not self.stacks:
return None
value = self.stacks[-1].pop()
if not self.stacks[-1]:
self.stacks.pop()
return value

def pop_at(self, index):
if index < 0 or index >= len(self.stacks):
return None
value = self.stacks[index].pop()
if not self.stacks[index]:
self.stacks.pop(index)
return value

def peek(self):
if not self.stacks:
return None
return self.stacks[-1][-1]
Ques:- There is a parking lot of cars that is full except for a single spot. Write some code to take it from one arbitrary configuration to another moving only one car at a time into the empty spot.
Asked In :-
Right Answer:
```python
def move_cars(parking_lot, start_config, end_config):
def find_empty_spot(parking_lot):
return parking_lot.index(None)

def swap(parking_lot, i, j):
parking_lot[i], parking_lot[j] = parking_lot[j], parking_lot[i]

current_config = start_config[:]
empty_spot = find_empty_spot(current_config)

while current_config != end_config:
for i in range(len(current_config)):
if current_config[i] == end_config[empty_spot]:
swap(current_config, i, empty_spot)
empty_spot = i
break

return current_config

# Example usage
parking_lot = [1, 2, 3, None, 4, 5]
start_config = [1, 2, 3, None, 4, 5]
end_config = [1,


The Algorithm category on takluu.com is designed to help candidates master the logic and efficiency behind solving complex coding problems. In technical interviews, especially in product-based and MNCs like Google, Microsoft, Amazon, and Infosys, algorithm-based questions test how well a candidate can think logically and solve real-world problems optimally.

An algorithm is a step-by-step procedure to solve a problem. Interviewers often look for candidates who can not only solve a problem but do so in the most efficient way possible—this includes optimizing time and space complexity. Topics such as recursion, sorting and searching algorithms, greedy techniques, dynamic programming, divide and conquer, backtracking, and graph algorithms are frequently asked.

Our platform offers a structured collection of real interview questions categorized by company, topic, and difficulty level. Each question comes with a detailed explanation, code implementation (in languages like C++, Java, and Python), and edge case handling strategies.

Whether you’re preparing for your first job or an advanced engineering position, understanding algorithmic patterns is crucial. We provide guides to help you identify these patterns, build solutions incrementally, and improve your problem-solving speed under time constraints.

With mock tests, scenario-based questions, and expert tips, Takluu ensures you’re not just memorizing solutions but truly understanding the logic behind them.

Mastering algorithms gives you an edge over other candidates and sets the foundation for efficient coding, system design, and real-time application development.

Start learning today and move one step closer to your dream job with our expertly curated algorithm resources.

AmbitionBox Logo

What makes Takluu valuable for interview preparation?

1 Lakh+
Companies
6 Lakh+
Interview Questions
50K+
Job Profiles
20K+
Users