The Wayback Machine - https://web.archive.org/web/20240915120937/https://www.geeksforgeeks.org/capacity-to-ship-packages-within-d-days/
Open In App

Capacity To Ship Packages Within D Days

Last Updated : 05 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array weights[] of n packages, the task is to find the least weight capacity of a boat to ship all Packages within d days. The weights[i] represent the weight of ith Package. Each day, we load the boat with packages without changing their order. We may not load more weight than the maximum weight capacity of the boat.

Example:

Input: weights[] = [1, 2, 3, 4, 5, 6, 7], d = 5
Output: 7
Explanation:

  • Day 1: Load the boat with packages [1, 2, 3] (total weight = 6).
  • Day 2: Load the boat with package [4] (total weight = 4).
  • Day 3: Load the boat with package [5] (total weight = 5).
  • Day 4: Load the boat with package [6] (total weight = 6).
  • Day 5: Load the boat with package [7] (total weight = 7).

The minimum capacity of boat needed is 7. With this capacity, we can ship all packages within 5 days by optimally distributing the packages as shown above.

Input: weights[] = [5, 2, 7, 4, 1, 4], d = 3
Output: 9
Explanation:

  • Day 1: Load the boat with packages [5, 2] (total weight = 7).
  • Day 2: Load the boat with packages [7] (total weight = 7).
  • Day 3: Load the boat with packages [4, 1, 4] (total weight = 9).

The minimum capacity needed is 9. We can ship all packages within 3 days by distributing the packages as shown above.

[Naive Approach] Using Iterative approach – O(n*sum) time and O(1) auxiliary space:

The very basic idea is to start with the minimum possible capacity of boat and gradually increase the capacity until we find a value that allows us to ship all packages within the given days.

To check if a capacity is sufficient, we iterate through the packages and try take cumulative sum of weights until we haven’t exceeded our chosen capacity of boat. If the current day’s weight exceeds the capacity, we start a new day. If all packages can be packed within the given days then this capacity is sufficient.

Code Implementation:

C++
#include <bits/stdc++.h>
using namespace std;

// Function to check if the current weight capacity can ship
// all weights within the given days
bool check(int weights[], int index, int sum, int remain,
           int n)
{
    // Current sum of weights for the current day
    int xsum = 0;
    // Number of days needed
    int cnt = 0;

    // Iterate over all weights
    for (int i = index; i < n; i++) {

        // Add weight to current day's sum
        xsum += weights[i];

        // If current day's sum exceeds or equals the
        // capacity
        if (xsum >= sum) {
            if (xsum == sum)

                // Reset current day's sum if it equals the
                // capacity
                xsum = 0;
            else
                // Start new day's sum with the current
                // weight
                xsum = weights[i];

            // Increment day count
            ++cnt;
        }

        // If remaining weights equal remaining days
        if (n - i == remain - cnt)

            // Return true indicating it's possible
            return true;
    }
    // If there's leftover weight for a new day
    if (xsum != 0)

        // Increment day count
        ++cnt;

    // Check if days needed equals the given days
    return cnt == remain;
}

// Function to find the least weight capacity of a boat
int leastWeightCapacity(int weights[], int n, int d)
{

    // Find the maximum weight in the array
    int m = *max_element(weights, weights + n);

    int i = 0;
    while (true) {

        // Check if the current weight capacity is
        // sufficient
        if (check(weights, i, m, d, n)) {

            // Return the weight capacity if sufficient
            return m;
        }

        // Increment weight capacity and check again
        ++m;
    }

    // Return the final weight capacity (unreachable code)
    return m;
}

// Driver code
int main()
{

    // Input weights
    int weights[] = { 1, 2, 3, 4, 5, 6, 7 };

    // Number of days
    int d = 5;

    // Number of weights
    int n = sizeof(weights) / sizeof(weights[0]);

    cout << leastWeightCapacity(weights, n, d) << endl;

    return 0;
}
Java
import java.util.Arrays;

public class Main {

    // Function to check if the current weight capacity can
    // ship all weights within the given days
    public static boolean check(int[] weights, int index,
                                int sum, int remain, int n)
    {
        // Current sum of weights for the current day
        int xsum = 0;

        // Number of days needed
        int cnt = 0;

        // Iterate over all weights
        for (int i = index; i < n; i++) {

            // Add weight to current day's sum
            xsum += weights[i];

            // If current day's sum exceeds or equals the
            // capacity
            if (xsum >= sum) {
                if (xsum == sum) {

                    // Reset current day's sum if it equals
                    // the capacity
                    xsum = 0;
                }
                else {
                    // Start new day's sum with the current
                    // weight
                    xsum = weights[i];
                }
                // Increment day count
                ++cnt;
            }

            // If remaining weights equal remaining days
            if (n - i == remain - cnt) {
                // Return true indicating it's possible
                return true;
            }
        }

        // If there's leftover weight for a new day
        if (xsum != 0) {
            // Increment day count
            ++cnt;
        }

        // Check if days needed equals the given days
        return cnt == remain;
    }

    // Function to find the least weight capacity of a boat
    public static int leastWeightCapacity(int[] weights,
                                          int n, int d)
    {
        // Find the maximum weight in the array
        int m = Arrays.stream(weights).max().getAsInt();

        int i = 0;
        while (true) {

            // Check if the current weight capacity is
            // sufficient
            if (check(weights, i, m, d, n)) {

                // Return the weight capacity if sufficient
                return m;
            }

            // Increment weight capacity and check again
            ++m;
        }
    }

    // Driver code
    public static void main(String[] args)
    {
        // Input weights
        int[] weights = { 1, 2, 3, 4, 5, 6, 7 };

        // Number of days
        int d = 5;

        // Number of weights
        int n = weights.length;

        System.out.println(
            leastWeightCapacity(weights, n, d));
    }
}
Python
def check(weights, index, sum, remain, n):
    # Current sum of weights for the current day
    xsum = 0
    # Number of days needed
    cnt = 0

    # Iterate over all weights
    for i in range(index, n):
        # Add weight to current day's sum
        xsum += weights[i]

        # If current day's sum exceeds or equals the capacity
        if xsum >= sum:
            if xsum == sum:
                # Reset current day's sum if it equals the capacity
                xsum = 0
            else:
                # Start new day's sum with the current weight
                xsum = weights[i]
            # Increment day count
            cnt += 1

        # If remaining weights equal remaining days
        if n - i == remain - cnt:
            # Return true indicating it's possible
            return True

    # If there's leftover weight for a new day
    if xsum != 0:
        # Increment day count
        cnt += 1

    # Check if days needed equals the given days
    return cnt == remain


def least_weight_capacity(weights, n, d):
    # Find the maximum weight in the array
    m = max(weights)

    i = 0
    while True:
        # Check if the current weight capacity is sufficient
        if check(weights, i, m, d, n):
            # Return the weight capacity if sufficient
            return m
        # Increment weight capacity and check again
        m += 1


# Driver code
weights = [1, 2, 3, 4, 5, 6, 7]
d = 5
n = len(weights)

print(least_weight_capacity(weights, n, d))
C#
using System;
using System.Linq;

public class Program {
    // Function to check if the current weight capacity can ship
    // all weights within the given days
    public static bool Check(int[] weights, int index, int sum, int remain, int n) {
        // Current sum of weights for the current day
        int xsum = 0;
        // Number of days needed
        int cnt = 0;

        // Iterate over all weights
        for (int i = index; i < n; i++) {
            // Add weight to current day's sum
            xsum += weights[i];

            // If current day's sum exceeds or equals the capacity
            if (xsum >= sum) {
                if (xsum == sum) {
                    // Reset current day's sum if it equals the capacity
                    xsum = 0;
                } else {
                    // Start new day's sum with the current weight
                    xsum = weights[i];
                }
                // Increment day count
                ++cnt;
            }

            // If remaining weights equal remaining days
            if (n - i == remain - cnt) {
                // Return true indicating it's possible
                return true;
            }
        }

        // If there's leftover weight for a new day
        if (xsum != 0) {
            // Increment day count
            ++cnt;
        }

        // Check if days needed equals the given days
        return cnt == remain;
    }

    // Function to find the least weight capacity of a boat
    public static int LeastWeightCapacity(int[] weights, int n, int d) {
        // Find the maximum weight in the array
        int m = weights.Max();

        int i = 0;
        while (true) {
            // Check if the current weight capacity is sufficient
            if (Check(weights, i, m, d, n)) {
                // Return the weight capacity if sufficient
                return m;
            }
            // Increment weight capacity and check again
            ++m;
        }
    }

    // Driver code
    public static void Main() {
        // Input weights
        int[] weights = { 1, 2, 3, 4, 5, 6, 7 };

        // Number of days
        int d = 5;

        // Number of weights
        int n = weights.Length;

        Console.WriteLine(LeastWeightCapacity(weights, n, d));
    }
}
JavaScript
function check(weights, index, sum, remain, n) {
    // Current sum of weights for the current day
    let xsum = 0;
    // Number of days needed
    let cnt = 0;

    // Iterate over all weights
    for (let i = index; i < n; i++) {
        // Add weight to current day's sum
        xsum += weights[i];

        // If current day's sum exceeds or equals the capacity
        if (xsum >= sum) {
            if (xsum === sum) {
                // Reset current day's sum if it equals the capacity
                xsum = 0;
            } else {
                // Start new day's sum with the current weight
                xsum = weights[i];
            }
            // Increment day count
            ++cnt;
        }

        // If remaining weights equal remaining days
        if (n - i === remain - cnt) {
            // Return true indicating it's possible
            return true;
        }
    }

    // If there's leftover weight for a new day
    if (xsum !== 0) {
        // Increment day count
        ++cnt;
    }

    // Check if days needed equals the given days
    return cnt === remain;
}

function leastWeightCapacity(weights, n, d) {
    // Find the maximum weight in the array
    let m = Math.max(...weights);

    let i = 0;
    while (true) {
        // Check if the current weight capacity is sufficient
        if (check(weights, i, m, d, n)) {
            // Return the weight capacity if sufficient
            return m;
        }
        // Increment weight capacity and check again
        ++m;
    }
}

// Driver code
const weights = [1, 2, 3, 4, 5, 6, 7];

// Number of days
const d = 5;

// Number of weights
const n = weights.length;

console.log(leastWeightCapacity(weights, n, d));

Output
7

Time Complexity: O(n*sum), where n is the number of weights and ‘sum’ is the sum of all weights.
Auxiliary Space: O(1), As we are using constant extra space.

[Expected Approach] Using Binary Search on Answer – O(n log(sum)) time and O(1) auxiliary space

We can use binary search on the answer to solve because this problem have a monotonic relationship: if a certain capacity C allows us to ship all packages within d days, any capacity greater than C will also work (and vice versa).

We start by determining the initial bounds:

The minimum capacity must be at least the weight of the heaviest package (since the boat needs to carry every package individually at a minimum), and the maximum capacity can be the sum of all package weights (if we could ship all packages in one trip). We then perform a binary search within these bounds.

For each midpoint capacity:

We simulate loading the packages onto the boat day by day, checking if the total number of days required is within the given limit. If the number of days exceeds the limit, we increase the lower bound of our search to look for a higher capacity. If it is within the limit, we decrease the upper bound to find if a lower capacity can still meet the requirement. This process continues until we find the minimum capacity that allows us to ship all packages within the given number of days.

Code Implementation:

C++
#include <bits/stdc++.h>
using namespace std;

// Function to find the least weight capacity of a truck.
int leastWeightCapacity(int weights[], int n, int d)
{
    int left = -1, right = 0;

    // Calculating the sum of all weights and finding the
    // maximum weight.
    for (int i = 0; i < n; i++) {
        right += weights[i];
        left = max(left, weights[i]);
    }

    // Performing binary search to find the least weight
    // capacity.
    while (left < right) {
        int mid = (left + right) / 2, need = 1, curr = 0;

        // Iterating over the weights and checking if the
        // current truck can carry up to the mid weight.
        for (int i = 0; i < n && need <= d;
             curr += weights[i++])
            if (curr + weights[i] > mid)
                // If the current truck cannot carry the
                // current weight, we need to use a new
                // truck and reset the current weight.
                curr = 0, need++;

        // If the number of trucks needed exceeds the given
        // limit, we need to increase the weight capacity
        // and update left.
        if (need > d)
            left = mid + 1;
        // If the number of trucks needed is within the
        // given limit, we can try to reduce the weight
        // capacity and update right.
        else
            right = mid;
    }
    // Returning the least weight capacity.
    return left;
}

// Driver code
int main()
{
    int weights[] = { 1, 2, 3, 4, 5, 6, 7 };
    int d = 5;
    int n = sizeof(weights) / sizeof(weights[0]);

    cout << leastWeightCapacity(weights, n, d) << endl;

    return 0;
}
Java
import java.util.Arrays;

public class Main {

    // Function to find the least weight capacity of a
    // truck.
    public static int leastWeightCapacity(int[] weights,
                                          int n, int d)
    {
        int left = Arrays.stream(weights).max().getAsInt();
        int right = Arrays.stream(weights).sum();

        // Performing binary search to find the least weight
        // capacity.
        while (left < right) {
            int mid = (left + right) / 2, need = 1,
                curr = 0;

            // Iterating over the weights and checking if
            // the current truck can carry up to the mid
            // weight.
            for (int i = 0; i < n; i++) {
                if (curr + weights[i] > mid) {
                    // If the current truck cannot carry the
                    // current weight, we need to use a new
                    // truck and reset the current weight.
                    curr = 0;
                    need++;
                }
                curr += weights[i];
            }

            // If the number of trucks needed exceeds the
            // given limit, we need to increase the weight
            // capacity and update left.
            if (need > d)
                left = mid + 1;
            // If the number of trucks needed is within the
            // given limit, we can try to reduce the weight
            // capacity and update right.
            else
                right = mid;
        }
        // Returning the least weight capacity.
        return left;
    }

    // Driver code
    public static void main(String[] args)
    {
        int[] weights = { 1, 2, 3, 4, 5, 6, 7 };
        int d = 5;
        int n = weights.length;

        System.out.println(
            leastWeightCapacity(weights, n, d));
    }
}
Python
def least_weight_capacity(weights, n, d):
    left = -1
    right = sum(weights)

    # Calculating the maximum weight
    for weight in weights:
        left = max(left, weight)

    # Performing binary search to find the least weight
    # capacity.
    while left < right:
        mid = (left + right) // 2
        need = 1
        curr = 0

        # Iterating over the weights and checking if the
        # current truck can carry up to the mid weight.
        for i in range(n):
            if curr + weights[i] > mid:
                curr = 0
                need += 1
            curr += weights[i]

        # If the number of trucks needed exceeds the given limit,
        # we need to increase the weight capacity and update left.
        if need > d:
            left = mid + 1
            
        # If the number of trucks needed is within the given limit,
        # we can try to reduce the weight capacity and update right.
        else:
            right = mid

    # Returning the least weight capacity.
    return left


# Driver code
weights = [1, 2, 3, 4, 5, 6, 7]
d = 5
n = len(weights)

print(least_weight_capacity(weights, n, d))
C#
using System;
using System.Linq;

class Program {
    // Function to find the least weight capacity of a
    // truck.
    static int LeastWeightCapacity(int[] weights, int n,
                                   int d)
    {
        int left = weights.Max();
        int right = weights.Sum();

        // Performing binary search to find the least weight
        // capacity.
        while (left < right) {
            int mid = (left + right) / 2;
            int need = 1, curr = 0;

            // Iterating over the weights and checking if
            // the
            // current truck can carry up to the mid weight.
            for (int i = 0; i < n; i++) {
                if (curr + weights[i] > mid) {
                  
                    // If the current truck cannot carry the
                    //  current weight, we need to use a new
                    // truck and reset the current weight.
                    curr = 0;
                    need++;
                }
                curr += weights[i];
            }

            // If the number of trucks needed exceeds the
            // given limit, we need to increase the weight
            // capacity and update left.
            if (need > d)
                left = mid + 1;
          
            // If the number of trucks needed is within the
            // given limit, we can try to reduce the weight
            // capacity and update right.
            else
                right = mid;
        }

        // Returning the least weight capacity.
        return left;
    }

    // Driver code
    static void Main()
    {
        int[] weights = { 1, 2, 3, 4, 5, 6, 7 };
        int d = 5;
        int n = weights.Length;

        Console.WriteLine(
            LeastWeightCapacity(weights, n, d));
    }
}
JavaScript
// Function to find the least weight capacity of a truck.
function leastWeightCapacity(weights, n, d) {
    let left = -1, right = 0;

    // Calculating the sum of all weights and
    // finding the maximum weight.
    for (let i = 0; i < n; i++) {
        right += weights[i];
        left = Math.max(left, weights[i]);
    }

    // Performing binary search to find the least weight capacity.
    while (left < right) {
        let mid = Math.floor((left + right) / 2);
        let need = 1, curr = 0;

        // Iterating over the weights and checking if
        // the current truck can carry up to the mid weight.
        for (let i = 0; i < n && need <= d; curr += weights[i++]) {
            if (curr + weights[i] > mid) {
            
                // If the current truck cannot carry the
                // current weight, we need to use a new truck 
                // and reset the current weight.
                curr = 0;
                need++;
            }
        }

        // If the number of trucks needed exceeds the
        // given limit, we need to increase the weight
        // capacity and update left.
        if (need > d) {
            left = mid + 1;
        } else {
        
            // If the number of trucks needed is within
            // the given limit, we can try to reduce the
            // weight capacity and update right.
            right = mid;
        }
    }

    // Returning the least weight capacity.
    return left;
}

// Driver code
let weights = [1, 2, 3, 4, 5, 6, 7];
let d = 5;
let n = weights.length;

console.log(leastWeightCapacity(weights, n, d));

Output
7

Time complexity: O(n log(sum)), where n is the number of weights and ‘sum’ is the sum of all weights.
Auxiliary Space: O(1)




Similar Reads

Biggest Reuleaux Triangle within a Square which is inscribed within a Circle
Given here is a circle of radius r, which inscribes a square which in turn inscribes a reuleaux triangle. The task is to find the maximum possible area of this reuleaux triangle.Examples: Input: r = 6 Output: 50.7434 Input: r = 11 Output: 170.554 Approach: From the figure, it is very clear that, if the side of the square is a, then a?2 = 2r a = ?2r
4 min read
Largest sphere that can be inscribed within a cube which is in turn inscribed within a right circular cone
Given here is a right circular cone of radius r and perpendicular height h, which is inscribed in a cube which in turn is inscribed in a sphere, the task is to find the radius of the sphere.Examples: Input: h = 5, r = 6 Output: 1.57306 Input: h = 8, r = 11 Output: 2.64156 Approach: Let the side of the cube = aLet the radius of the sphere = RWe know
4 min read
Largest ellipse that can be inscribed within a rectangle which in turn is inscribed within a semicircle
Given here is a semicircle of radius r, which inscribes a rectangle which in turn inscribes an ellipse. The task is to find the area of this largest ellipse.Examples: Input: r = 5 Output: 19.625 Input: r = 11 Output: 94.985 Approach: Let the, length of the rectangle = l and breadth of the rectangle = bLet, the length of the major axis of the ellips
4 min read
Minimum work to be done per day to finish given tasks within D days
Given an array task[] of size N denoting amount of work to be done for each task, the problem is to find the minimum amount of work to be done on each day so that all the tasks can be completed in at most D days. Note: On one day work can be done for only one task. Examples: Input: task[] = [3, 4, 7, 15], D = 10Output: 4Explanation: Here minimum wo
9 min read
Maximum items that can be filled in K Knapsacks of given Capacity
Given an integer array W[] consisting of weights of items and 'K' knapsacks of capacity 'C', find maximum weight we can put in the knapsacks if breaking of an item is not allowed. Examples: Input : w[] = {3, 9, 8}, k = 1, c = 11 Output : 11 The required subset will be {3, 8} where 3+8 = 11 Input : w[] = {3, 9, 8}, k = 1, c = 10 Output : 9 We will u
11 min read
Find the minimum capacity of the train required to hold the passengers
Given the number of passengers entering and exiting the train, the task is to find the minimum capacity of the train to keep all the passengers in throughout the journey.Examples: Input: enter[] = {3, 5, 2, 0}, exit[] = {0, 2, 4, 4} Output: 6 Station 1: Train capacity = 3 Station 2: Train capacity = 3 + 5 - 2 = 6 Station 3: Train capacity = 6 + 2 -
5 min read
Minimum capacity of small arrays needed to contain all element of the given array
Given an array of positive integers and a value K, The task is to empty the array in less than or equal to K small arrays such that each small array can only contain at max P elements from a single slot / index of the given array. Find the minimum value of P.Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 7 Output: 3Explanation: We put 1 into the fir
9 min read
Maximum possible value of array elements that can be made based on given capacity conditions
Given two arrays arr[] and cap[] both consisting of N positive integers such that the ith element cap[i] denotes the capacity of arr[i], the task is to find the maximum possible value of array elements that can be made such that it is allowed to decrease an array element arr[i] by some arbitrary value and increment any of its adjacent element by th
5 min read
Minimum steps required to reach the end of Array with a given capacity
Given an array arr[] of size n. You will have to traverse the array from left to right deducting each element of the array from the initial capacity, such that your initial capacity should never go below 0. In case, the current capacity is less than the current element, we can traverse back to the start of the array to refill our capacity, and then
15 min read
Count number of distinct sum subsets within given range
Given a set S of N numbers and a range specified by two numbers L (Lower Bound) and R (Upper Bound). Find the number of distinct values of all possible sums of some subset of S that lie between the given range. Examples : Input : S = { 1, 2, 2, 3, 5 }, L = 1 and R = 5 Output : 5 Explanation : Every number between 1 and 5 can be made out using some
8 min read
Numbers within a range that can be expressed as power of two numbers
Given two integers L and R. Find the number of perfect powers in the given range [L, R]. A number x is said to be perfect power if there exists some integers a &gt; 0, p &gt; 1 such that x = ap. Examples : Input : 1 4 Output : 2 Explanation : Suitable numbers are 1 and 4 where 1 can be expressed as 1 = 12 and 4 can be expressed as 4 = 22 Input : 12
12 min read
Print direction of moves such that you stay within the [-k, +k] boundary
Given an array, arr[] of N positive integers and an integer K. It is given that you start at position 0 and you can move to left or right by a[i] positions starting from arr[0]. The task is to print the direction of moves so that you can complete N steps without exceeding the [-K, +K] boundary by moving right or left. In case you cannot perform ste
7 min read
Area of circle inscribed within rhombus
Given a rhombus with diagonals a and b, which contains an inscribed circle. The task is to find the area of that circle in terms of a and b.Examples: Input: l = 5, b = 6Output: 11.582 Input: l = 8, b = 10Output: 30.6341 Approach: From the figure, we see, the radius of inscribed circle is also a height h=OH of the right triangle AOB. To find it, we
4 min read
Arrange a binary string to get maximum value within a range of indices
Given a string consisting of only 0's and 1's. Now you are given N non-intersecting ranges L, R ( L &lt;= R), more specifically [L1, R1], [L2, R2], ..., [LN, RN], No two of these intervals overlap — formally, for each valid i, j such that i!=j, either Ri&lt;Lj or Rj&lt;Li. The task is to find a valid permutation that will hold two following conditi
8 min read
Program to find the side of the Octagon inscribed within the square
Given a square of side length 'a', the task is to find the side length of the biggest octagon that can be inscribed within it. Examples: Input: a = 4 Output: 1.65685 Input: a = 5 Output: 2.07107 Approach: =&gt; From the figure, it can be seen that, side length of the Octagon = b =&gt; Also since the polygons are regular, therefore 2*x + b = a =&gt;
4 min read
All possible co-prime distinct element pairs within a range [L, R]
Given a range [L, R], the task is to find all possible co-prime pairs from the range such that an element doesn't appear in more than a single pair.Examples: Input : L=1 ; R=6 Output : 3 The answer is 3 [(1, 2) (3, 4) (5, 6)], all these pairs have GCD 1. Input : L=2 ; R=4 Output : 1 The answer is 1 [(2, 3) or (3, 4)] as '3' can only be chosen for a
4 min read
Largest cube that can be inscribed within the sphere
Given here is a sphere of radius r, the task is to find the side of the largest cube that can fit inside in it.Examples: Input: r = 8 Output: 9.2376 Input: r = 5 Output: 5.7735 Approach: Side of the cube = a Radius of the sphere = r From the diagonal, it is clear that, diagonal of the cube = diameter of the sphere, a?3 = 2r or, a = 2r/?3 Below is t
3 min read
Largest cone that can be inscribed within a cube
Given here is a cube of side length a. We have to find the height and the radius of the biggest right circular cone that can be inscribed within it.Examples: Input : a = 6 Output : r = 4.24264, h = 6 Input : a = 10 Output : r = 7.07107, h = 10 Approach: Let height of the cone = h. and, radius of the cone = r.From the diagram, we can clearly underst
5 min read
Largest cube that can be inscribed within a right circular cone
Given a right circular cone of radius r and perpendicular height h. We have to find the side length of the biggest cube that can be inscribed within it.Examples: Input : h = 5, r = 6 Output : 3.14613 Input : h = 8, r = 12 Output : 5.43698 Approach: Let, side of the cube = a.From the diagram, we can clearly understand using the properties of triangl
4 min read
Sum of all odd length palindromic numbers within the range [L, R]
Given two integers [Tex]L [/Tex]and [Tex]R [/Tex], the task is to find the sum of all the palindromic numbers within the range [L, R] which are of odd length.Examples: Input: L = 10, R = 130 Output: 333 101 + 111 + 121 = 333Input: L = 110, R = 1130 Output: 49399 Approach: Iterate from [Tex]L [/Tex]to [Tex]R [/Tex]and for every number check whether
10 min read
Largest cube that can be inscribed within a right circular cylinder
Given here is a right circular cylinder of height h and radius r. The task is to find the volume of biggest cube that can be inscribed within it.Examples: Input: h = 3, r = 2 Output: volume = 27 Input: h = 5, r = 4 Output: volume = 125 Approach: From the figure, it can be clearly understand that side of the cube = height of the cylinder. So, the vo
4 min read
Largest right circular cylinder within a frustum
Given a frustum of height [Tex]h [/Tex], top-radius [Tex]r [/Tex]&amp; base-radius [Tex]R [/Tex]. The task is to find the volume of biggest right circular cylinder that can be inscribed within it.Examples: Input : r = 5, R = 10, h = 4 Output : 314 Input : r = 7, R = 11, h = 6 Output : 923.16 Approach: Let: The height of the cylinder = h1Radius of t
5 min read
Largest Square that can be inscribed within a hexagon
Given a regular hexagonof side length a, the task is to find the area of the largest square that can be inscribed within it.Examples: Input: a = 6 Output: 57.8817Input: a = 8 Output: 102.901 Approach: The square we will derive will have the same centre and axes of the hexagon. This is because the square will become smaller if we will rotate it. The
4 min read
Area of the biggest ellipse inscribed within a rectangle
Given here is a rectangle of length l &amp; breadth b, the task is to find the area of the biggest ellipse that can be inscribed within it.Examples: Input: l = 5, b = 3 Output: 11.775 Input: 7, b = 4 Output: 21.98 Approach: Let, the length of the major axis of the ellipse = 2x and the length of the minor axis of the ellipse = 2yFrom the diagram, it
4 min read
Check if the robot is within the bounds of the grid after given moves
Given a grid of size N X M and a robot is placed at cell (N - 1, M - 1). Also, given string str which consists only of the characters 'U' (Up), 'D' (Down), 'L' (Left) and 'R' (Right) representing the moves the robot is going to perform within the grid. The task is to find whether the robot will be safe at the end of the last move. Robot is said to
9 min read
Print all neighbour nodes within distance K
Given a graph of N nodes, E edges, a node X and a distance K. The task is to print all the nodes within the distance K from X. Input: Output: 4 5 2 7 3Neighbour nodes within distance 2 of node 4 are: 4 5 2 7 3 Approach: To print all the nodes that are at distance K or less than K. We can do it by applying dfs variation, that takes K node from where
8 min read
Distribution of a Number in Array within a Range
Given the integers S, N, K, L, and R where S has to be distributed in an array of size N such that each element must be from the range [L, R] and the sum of K elements of the array should be greater than the sum of the remaining N - K elements whose sum is equal to Sk and these elements are in non-increasing order. Examples: Input: N = 5, K = 3, L
9 min read
Maximum neighbor element in a matrix within distance K
Given a matrix mat[][] and an integer K, the task is to find the maximum neighbor within an absolute distance of K for each element of the matrix.In other words for each Matrix[i][j] find maximum Matrix[p][q] such that abs (i-p) + abs (j-q) ? K.Examples: Input: mat[][] = {{1, 2}, {4, 5}}, K = 1 Output: {{4, 5}, {5, 5}} Explanation: Maximum neighbou
8 min read
Queries to find frequencies of a string within specified substrings
Given a string S and a matrix Q of queries, each specifying the starting and ending indices L( = Q[i][0]) and R( = Q[i][0]) respectively of a substring of S, the task is to find the frequency of string K in substring [L, R]. Note: The ranges follow the 1-based indexing. Examples: Input: S = "GFGFFGFG", K = "GFG", Q = {{1, 8}, {3, 5}, {5, 8}} Output
5 min read
Find N random points within a Circle
Given four integers N, R, X, and Y such that it represents a circle of radius R with [X, Y] as coordinates of the center. The task is to find N random points inside or on the circle. Examples: Input: R = 12, X = 3, Y = 3, N = 5 Output: (7.05, -3.36) (5.21, -7.49) (7.53, 0.19) (-2.37, 12.05) (1.45, 11.80)Input: R = 5, X = 1, Y = 1, N = 3 Output: (4.
6 min read