
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find squared elements list in sorted order in Python
Suppose we have a list of numbers called nums, where elements are sorted in ascending order, we have to square the elements and return the result in sorted order.
So, if the input is like nums = [-8, -3, 0, 5, 6], then the output will be [0, 9, 25, 36, 64]
To solve this, we will follow these steps −
- n := size of nums
- l := 0
- r := n - 1
- index := n - 1
- res := a list of size same as nums and fill it with 0
- while index >= 0, do
- if |nums[l]| > |nums[r]|, then
- res[index] := nums[l] * nums[l]
- l := l + 1
- otherwise,
- res[index] := nums[r] * nums[r]
- r := r - 1
- index := index - 1
- if |nums[l]| > |nums[r]|, then
- return res
Example
Let us see the following implementation to get better understanding −
def solve(nums): n = len(nums) l = 0 r = n - 1 index = n - 1 res = [0 for i in range(len(nums))] while index >= 0: if abs(nums[l]) > abs(nums[r]): res[index] = nums[l] * nums[l] l += 1 else: res[index] = nums[r] * nums[r] r -= 1 index -= 1 return res nums = [-8, -3, 0, 5, 6] print(solve(nums))
Input
[-8, -3, 0, 5, 6]
Output
[0, 9, 25, 36, 64]
- Related Articles
- Python program to find common elements in three sorted arrays?
- Python - Inserting item in sorted list maintaining order
- Program to merge two sorted list to form larger sorted list in Python
- To print all elements in sorted order from row and column wise sorted matrix in Python
- Square list of elements in sorted form in Python
- Python program to find sum of elements in list
- Python Program to extracts elements from a list with digits in increasing order
- Program to find all prime factors of a given number in sorted order in Python
- Program to find the number of unique integers in a sorted list in Python
- Find sum of elements in list in Python program
- Program to get indices of a list after deleting elements in ascending order in Python
- Finding relative order of elements in list in Python
- Java program to find common elements in three sorted arrays
- C# program to find common elements in three sorted arrays
- Program to find only even indexed elements from list in Python

Advertisements