WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Data Structures & Algorithms · Intermediate · question 40 of 100

What is the concept of greedy algorithms, and how do they differ from other algorithmic approaches? Provide an example of a problem solved using a greedy algorithm.?

📕 Buy this interview preparation book: 100 Data Structures & Algorithms questions & answers — PDF + EPUB for $5

A greedy algorithm is an algorithmic paradigm that makes the locally optimal choice at each step in the hope of finding a global optimum solution. In other words, the algorithm chooses the best option available at the current moment without worrying about the future implications of that choice. Greedy algorithms are typically simple, efficient, and easy to implement.

One of the key characteristics of greedy algorithms is that they do not necessarily always produce the optimal solution. In some cases, a greedy approach may lead to a suboptimal solution that is still reasonably good but not the best possible outcome. In other cases, a greedy approach may fail to find any solution at all.

A classic example of a problem that can be solved using a greedy algorithm is the fractional knapsack problem. In this problem, we are given a set of items, each with a weight and a value, and a knapsack that can hold a certain weight limit. The goal is to fill the knapsack with items that maximize the total value while respecting the weight limit.

The greedy approach to this problem involves sorting the items by their value-to-weight ratio and then adding items to the knapsack in descending order of this ratio until the knapsack is full. This approach works because it selects the most valuable items first, while still respecting the weight limit.

Here’s an example implementation of the fractional knapsack problem in Java:

public static double fractionalKnapsack(int[] values, int[] weights, int capacity) {
    int n = values.length;
    double[] ratios = new double[n];
    for (int i = 0; i < n; i++) {
        ratios[i] = (double) values[i] / weights[i];
    }
    double maxVal = 0.0;
    while (capacity > 0 && maxRatio > 0) {
        int index = getMaxRatioIndex(ratios);
        if (weights[index] <= capacity) {
            maxVal += values[index];
            capacity -= weights[index];
        } else {
            maxVal += ratios[index] * capacity;
            capacity = 0;
        }
        ratios[index] = 0;
    }
    return maxVal;
}

private static int getMaxRatioIndex(double[] ratios) {
    int maxIndex = 0;
    double maxRatio = 0;
    for (int i = 0; i < ratios.length; i++) {
        if (ratios[i] > maxRatio) {
            maxRatio = ratios[i];
            maxIndex = i;
        }
    }
    return maxIndex;
}

In this implementation, the fractionalKnapsack method takes as input an array of item values values, an array of item weights weights, and the capacity of the knapsack capacity. The method first computes the value-to-weight ratios of all the items and then repeatedly selects the item with the highest ratio until the knapsack is full or there are no more items left. The getMaxRatioIndex method is a helper method that returns the index of the item with the highest ratio. The method returns the maximum total value that can be obtained from the items that fit in the knapsack.

Overall, the greedy approach to the fractional knapsack problem is efficient and provides a good approximate solution to the problem. However, it does not always produce the optimal solution in all cases, and there may be other algorithmic approaches that provide better results in some scenarios.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Data Structures & Algorithms interview — then scores it.
📞 Practice Data Structures & Algorithms — free 15 min
📕 Buy this interview preparation book: 100 Data Structures & Algorithms questions & answers — PDF + EPUB for $5

All 100 Data Structures & Algorithms questions · All topics