algoadvance

Leetcode 2525. Categorize Box According to Criteria

Problem Statement

You are given four integers length, width, height, and mass that describe a box. The box can be categorized based on the following criteria:

  1. A box is considered Bulky if any of the following dimensions is true:
    • The box’s volume is at least (10^9) (volume = length * width * height).
    • Any dimension (length, width, or height) is at least (10^4).
  2. A box is considered Heavy if its mass is at least 100.

The box could fall into one of the four following categories:

Write a function string categorizeBox(int length, int width, int height, int mass) that returns the category of the box.

Clarifying Questions

  1. Are the input dimensions and mass always positive integers?
  2. Can we assume that the values of length, width, height, and mass do not overflow standard integer ranges in C++?

Strategy

  1. Determine the Bulky Condition:
    • Calculate the volume and see if it is (\ge 10^9).
    • Check each dimension to see if any is (\ge 10^4).
  2. Determine the Heavy Condition:
    • Check if the mass is (\ge 100).
  3. Combine the Conditions:
    • Use conditional logic to ascertain which category the box falls into based on the conditions evaluated.

Code

#include <iostream>
using namespace std;

string categorizeBox(int length, int width, int height, int mass) {
    // Determine if the box is Bulky.
    const long long volume = static_cast<long long>(length) * width * height;  // Use long long to avoid overflow
    bool isBulky = (volume >= 1000000000) || (length >= 10000) || (width >= 10000) || (height >= 10000);
    
    // Determine if the box is Heavy.
    bool isHeavy = (mass >= 100);
    
    // Determine the category.
    if (isBulky && isHeavy) {
        return "Both";
    } else if (isBulky) {
        return "Bulky";
    } else if (isHeavy) {
        return "Heavy";
    } else {
        return "Neither";
    }
}

// Sample Driver Code
int main() {
    // Example cases
    cout << categorizeBox(10000, 2000, 3000, 101) << endl; // Output: Both
    cout << categorizeBox(10000, 2000, 300, 50) << endl;   // Output: Bulky
    cout << categorizeBox(10, 20, 30, 200) << endl;        // Output: Heavy
    cout << categorizeBox(10, 20, 30, 50) << endl;         // Output: Neither
    
    return 0;
}

Time Complexity

The time complexity of the solution is (O(1)) since it involves a constant number of arithmetic operations and comparisons, regardless of the size of the input values. The operations themselves are basic and do not depend on input size.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI