Categorize Box According to Criteria Problem
#2525
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2525.
Given four integers length, width, height, and mass, representing the dimensions and mass of a box, respectively, return a string representing the category of the box.
- The box is
"Bulky"if:- Any of the dimensions of the box is greater or equal to
10^4. - Or, the volume of the box is greater or equal to
10^9.
- Any of the dimensions of the box is greater or equal to
- If the mass of the box is greater or equal to
100, it is"Heavy". - If the box is both
"Bulky"and"Heavy", then its category is"Both". - If the box is neither
"Bulky"nor"Heavy", then its category is"Neither". - If the box is
"Bulky"but not"Heavy", then its category is"Bulky". - If the box is
"Heavy"but not"Bulky", then its category is"Heavy".
Note that the volume of the box is the product of its length, width and height.
Example 1:
Input: length = 1000, width = 35, height = 700, mass = 300
Output: "Heavy"
Explanation:
None of the dimensions of the box is greater or equal to 10^4.
Its volume = 24500000 <= 10^9. So it cannot be categorized as "Bulky".
However mass >= 100, so the box is "Heavy".
Since the box is not "Bulky" but "Heavy", we return "Heavy".
Example 2:
Input: length = 200, width = 50, height = 800, mass = 50
Output: "Neither"
Explanation:
None of the dimensions of the box is greater or equal to 10^4.
Its volume = 8 * 10^6 <= 10^9. So it cannot be categorized as "Bulky".
Its mass is also less than 100, so it cannot be categorized as "Heavy" either.
Since its neither of the two above categories, we return "Neither".
Constraints:
1 <= length, width, height <= 10^51 <= mass <= 10^3
Solution
Approach: Simulation
Follow the statement directly. The box is bulky if any dimension is at least 10^4 or its volume is at least 10^9 (the volume can reach 10^12, so use a 64-bit type in Java, C++ and Go). It is heavy if the mass is at least 100. Encode bulky as bit 0 and heavy as bit 1, and use the resulting number to pick among Neither, Bulky, Heavy and Both.
Complexity: O(1) time and O(1) space.
class Solution:
def categorizeBox(self, length: int, width: int, height: int, mass: int) -> str:
v = length * width * height
bulky = int(any(x >= 10000 for x in (length, width, height)) or v >= 10**9)
heavy = int(mass >= 100)
i = heavy << 1 | bulky
d = ['Neither', 'Bulky', 'Heavy', 'Both']
return d[i]