Syntax error Check if the array is beautiful in Python

Check if the array is beautiful in Python



Suppose we have an array nums of unique elements. We have to check whether these conditions satisfy or not:

  1. Elements will be in range 1 to n.
  2. The array must not be sorted in ascending order.

So, if the input is like nums = [2,6,1,5,3,4], then the output will be True.

To solve this, we will follow these steps −

  • n := size of nums
  • total := nums[0]
  • is_sorted := True
  • for i in range 1 to n - 1, do
    • if nums[i] is same as nums[i - 1], then
      • return False
    • if nums[i] < nums[i - 1], then
      • is_sorted := False
    • total := total + nums[i]
  • if is_sorted is true, then
    • return False
  • return true when total is same as sum of first n numbers, otherwise false

Let us see the following implementation to get better understanding −

Example Code

Live Demo

def solve(nums):
   n = len(nums)
   
   total = nums[0]
   is_sorted = True
   
   for i in range(1,n):
      if nums[i] == nums[i - 1]:
         return False
  
      if nums[i] < nums[i - 1]:
         is_sorted = False
      total += nums[i]
   
   if is_sorted:
      return False
  
   return total == (n * (n + 1) // 2)
 
nums = [2,6,1,5,3,4]
print(solve(nums))

Input

[2,6,1,5,3,4]

Output

True
Updated on: 2021-01-15T06:29:51+05:30

567 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements