# Check if the array is beautiful in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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

nums = [2,6,1,5,3,4]
print(solve(nums))

## Input

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


## Output

True
Updated on 15-Jan-2021 06:29:51