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

PythonServer Side ProgrammingProgramming

Suppose we have an array nums containing size of n different cubes, they are placed horizontally. We have to make a pile of cubes vertically. The new cube should follow −

  • if ith cube is on top of jth cube, then side length of jth one must be greater or equal to side length of ith one.

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

So, if the input is like nums = [1,2,3,7,8], then the output will be True because we can take boxes from right to left to pile them up successfully.

To solve this, we will follow these steps −

  • n := size of nums
  • d := make a double ended queue from the elements of nums
  • flag := True
  • prev := 0
  • while d is not empty, do
    • first := d[0]
    • last := d[n-1]
    • if prev is not same as 0 and (first > prev or last > prev) , then
      • flag := False
      • come out from the loop
    • if first >= last, then
      • prev := left item of d, and delete it from d
    • otherwise,
      • prev := last item of d and delete it from d
  • if flag is true, then
    • return True
  • otherwise,
    • return False

Example

Let us see the following implementation to get better understanding

from collections import deque
def solve(nums):
   n = len(nums)
   d = deque(nums)
   flag = True
   prev = 0
   while d:
      first = d[0]
      last = d[-1]
      if prev != 0 and (first > prev or last > prev):
         flag = False
         break
      if first >= last:
         prev = d.popleft()
      else:
         prev = d.pop()
   if flag:
      return True
   else:
      return False

nums = [1,2,3,7,8]
print(solve(nums))

Input

[1,2,3,7,8]

Output

True
raja
Published on 12-Oct-2021 08:14:01
Advertisements