Similar Problems

Similar Problems not available

Sort Array By Parity - Leetcode Solution

LeetCode:  Sort Array By Parity Leetcode Solution

Difficulty: Easy

Topics: sorting array two-pointers  

Problem Statement:

Given an integer array nums, you need to sort the odd numbers in ascending order and the even numbers in descending order.

Example 1:

Input: nums = [3,1,2,4] Output: [4,2,1,3] Explanation: Odd numbers are [3,1] and their ascending order is [1,3]. Even numbers are [2,4] and their descending order is [4,2]. Example 2:

Input: nums = [0] Output: [0]

Solution:

One of the simplest solutions is to use two lists. One list will contain all the even integers from the given array in descending order, and another list will contain all the odd integers in ascending order. Once we have these two lists, we can merge them and get the desired output.

Let's write down the solution step by step:

Create an empty list for even integers, and another for odd integers. Loop through all the integers in the given array and check if an integer is even or odd. If it is even, add it to the even list, and if it is odd, add it to the odd list. Sort the even list in descending order and sort the odd list in ascending order. Merge both the lists and return the merged list.

Example code in Python:

def sortArrayByParity(nums): evenList = [] oddList = [] for num in nums: if num % 2 == 0: evenList.append(num) else: oddList.append(num) evenList.sort(reverse=True) oddList.sort() return evenList + oddList

nums = [3,1,2,4] print(sortArrayByParity(nums))

The output will be: [4, 2, 1, 3]

The time complexity of this solution is O(nlogn), where n is the length of the given array. The space complexity is also O(n), where n is the length of the given array.

Sort Array By Parity Solution Code

1