712107. Koko Eating Bananas

Medium

Koko Eating Bananas

Slug: koko-eating-bananas

Difficulty: Medium

Id: 712107

Topic Tags: Binary Search, Arrays

Company Tags: Bloomberg, Amazon, Microsoft, Walmart, Adobe, Arcesium, Uber

Summary

Koko is eating bananas. She eats them in a specific order and we need to find the minimum number of operations required for her to finish eating all the bananas. This problem can be solved using binary search.

Detailed Explanation

The problem statement says that Koko has N bananas and she will eat them one by one from left to right. If she eats an even-indexed banana, she will skip the next one, but if she eats an odd-indexed banana, she will also eat the next one. We need to find the minimum number of operations required for her to finish eating all the bananas.

To solve this problem, we can use binary search. We first sort the array and then perform a binary search on it. The idea is that if Koko eats an even-indexed banana at the beginning, she will skip the next one. If she eats an odd-indexed banana, she will also eat the next one.

Here is a step-by-step breakdown of the solution:

  1. Initialize two pointers, low and high, to the start and end of the array.
  2. While low < high:
    • Calculate mid as (low + high) / 2.
    • If mid is even, calculate newLow as mid + 1.
    • Otherwise, calculate newHigh as mid - 1.
  3. Return the minimum number of operations required for Koko to finish eating all the bananas.

The time complexity of this solution is O(logN) and the space complexity is O(1).

Optimized Solutions

Java

View on GeeksforGeeks
public class Solution {
    public int kokoEatingBananas(int[] piles) {
        Arrays.sort(piles);
        int low = 0, high = piles.length;
        while (low < high) {
            int mid = (low + high) / 2;
            if ((mid % 2 == 1 && piles[mid] <= piles[high - 1]) || (mid % 2 == 0 && piles[mid] >= piles[high - 1])) {
                high = mid;
            } else {
                low = mid + 1;
            }
        }
        return piles.length - low;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.