Python program to check whether we can pile up cubes or not

Suppose we have an array nums containing sizes of n different cubes placed horizontally. We need to make a vertical pile of cubes following this rule:

  • If the ith cube is on top of the jth cube, then the side length of the jth cube must be greater than or equal to the side length of the ith cube.

When making the vertical pile, we can only take cubes from the left side or right side, but not from the middle. We need to check whether we can pile them up successfully or not.

Problem Example

If the input is nums = [1,2,3,7,8], then the output will be True because we can take cubes from right to left (8?7?3?2?1) to pile them up successfully.

Algorithm Steps

To solve this problem, we follow these steps:

  • Create a double-ended queue from the array elements
  • Use a greedy approach: always pick the smaller cube from either end
  • Check if the selected cube can be placed on top of the previous cube
  • Continue until all cubes are processed or an invalid placement is found

Implementation

Let's implement the solution using a deque data structure:

from collections import deque

def can_pile_cubes(nums):
    if not nums:
        return True
    
    d = deque(nums)
    prev = 0  # Size of the previous cube placed
    
    while d:
        first = d[0]   # Left cube
        last = d[-1]   # Right cube
        
        # If both cubes are larger than previous, it's impossible
        if prev != 0 and (first > prev or last > prev):
            return False
        
        # Choose the smaller cube (greedy approach)
        if first >= last:
            prev = d.popleft()  # Take from left
        else:
            prev = d.pop()      # Take from right
    
    return True

# Test the function
nums = [1, 2, 3, 7, 8]
result = can_pile_cubes(nums)
print(f"Can pile cubes {nums}: {result}")

# Test with another example
nums2 = [3, 1, 4, 2]
result2 = can_pile_cubes(nums2)
print(f"Can pile cubes {nums2}: {result2}")
Can pile cubes [1, 2, 3, 7, 8]: True
Can pile cubes [3, 1, 4, 2]: False

How It Works

The algorithm uses a greedy approach:

  • Step 1: Compare cubes at both ends of the remaining array
  • Step 2: Always choose the smaller cube to place next (this maximizes our chances)
  • Step 3: Check if the chosen cube can be validly placed on top of the previous one
  • Step 4: If any cube violates the stacking rule, return False

Example Walkthrough

For nums = [1, 2, 3, 7, 8]:

  • Compare 1 and 8 ? choose 1 (smaller)
  • Compare 2 and 8 ? choose 2 (smaller)
  • Compare 3 and 8 ? choose 3 (smaller)
  • Compare 7 and 8 ? choose 7 (smaller)
  • Only 8 remains ? choose 8

Final stack: 8 (bottom) ? 7 ? 3 ? 2 ? 1 (top). This is valid since each cube is smaller than or equal to the one below it.

Conclusion

This greedy algorithm efficiently determines if cubes can be stacked by always choosing the smaller available cube from either end. The time complexity is O(n) and space complexity is O(n) for the deque.

Updated on: 2026-03-26T15:41:01+05:30

375 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements