Question 1
EasyWhat is a greedy algorithm?
- A.
One that uses a lot of memory
Popular companies
Prepare company by company
Hiring pattern, syllabus, past questions and mocks for each company.
All companiesPractice by subject
Data Structures and Algorithms
What is a greedy algorithm?
One that uses a lot of memory
One that makes the locally best choice at each step, hoping for a global optimum
One that tries every possibility
One that always uses recursion
Answer: B
Greedy works only for problems with the greedy-choice property and optimal substructure.
Which problem is solved optimally by a greedy approach?
Activity selection (maximum non-overlapping intervals)
Longest common subsequence
0/1 knapsack
Travelling salesman
Answer: A
Choosing the activity that ends earliest is always safe.
Which algorithm builds a minimum spanning tree greedily by adding the cheapest edge that doesn't form a cycle?
Floyd–Warshall
Kruskal's algorithm
Dijkstra's algorithm
Bellman-Ford
Answer: B
Prim's algorithm is another greedy MST algorithm, growing one tree from a start vertex.
Which coding scheme builds optimal prefix codes greedily by merging the two least frequent symbols?
Base64
Huffman coding
ASCII
Run-length encoding
Answer: B
Frequent symbols get shorter codes, minimising the total encoded length.
What is the output of this code?
coins, amt, n = [10, 5, 2], 17, 0
for c in coins:
n += amt // c
amt %= c
print(n)
2
5
Answer: D
Greedy change takes as many of the largest coin as possible, then the next: 17 = 10 + 5 + 2, so 3 coins. (Greedy is optimal for such canonical coin systems.)
For which problem can a greedy approach give a wrong answer?
Huffman coding
Coin change with coins {1, 3, 4} for amount 6
Activity selection
Fractional knapsack
Answer: B
Greedy picks 4 + 1 + 1 (3 coins), but 3 + 3 uses only 2.
In the fractional knapsack problem, in what order are items taken?
By highest value per unit weight first
By highest value first
In input order
By lowest weight first
Answer: A
Taking the best value-to-weight ratio first (with a fraction of the last item) is optimal.
At each step, what does a greedy algorithm choose?
Every option, to compare them all
A random option
The option that looks worst
The option that looks best right now
Answer: D
It never reconsiders earlier choices.
Using coins of ₹1, ₹2, ₹5 and ₹10, how many coins does the greedy method use to pay ₹38?
6
5
4
7
Answer: A
10 + 10 + 10 + 5 + 2 + 1 = 38: six coins.
In the activity-selection problem, which activity does the greedy algorithm pick next?
The compatible activity that finishes earliest
The activity that starts latest
The longest activity
A random activity
Answer: A
Finishing early leaves the most time for the remaining activities.
4
3