- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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:
- Elements will be in range 1 to n.
- 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 nums[i] is same as nums[i - 1], then
- 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
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
Advertisements