Similar Problems

Similar Problems not available

Sort The Jumbled Numbers - Leetcode Solution

Companies:

LeetCode:  Sort The Jumbled Numbers Leetcode Solution

Difficulty: Medium

Topics: sorting array  

Problem Statement:

Given an array of integers, sort the array in non-decreasing order in a way such that the odd numbers appear before even numbers. The relative order of odd and even numbers should remain the same as in the original array.

Example 1:

Input: [4,2,5,7] Output: [5,7,4,2]

Example 2:

Input: [3,1,2,4] Output: [3,1,2,4]

Explanation:

In the first example, the odd numbers are 5 and 7 and they appear before the even numbers 4 and 2, which are sorted in non-decreasing order. In the second example, the odd numbers are 3 and 1 and they already appear before the even numbers 2 and 4.

Solution:

One possible solution to this problem is to use two pointers, one starting from the beginning of the array and the other starting from the end of the array. We can exchange the positions of the odd and even elements using these pointers until they overlap. By doing so, we can ensure that the odd elements appear before the even elements in the sorted array.

We can implement this solution using the following steps:

Step 1: Initialize two pointers, i and j, such that i points to the first element and j points to the last element of the array.

Step 2: Repeat the following steps until i>=j:

a) If the element at index i is odd, move to the next element by incrementing i. b) If the element at index j is even, move to the previous element by decrementing j. c) If the element at index i is even and the element at index j is odd, swap them and move to the next element by incrementing i and decrementing j. d) If both the elements at index i and j are odd or even, or if i is pointing to an even element and j is pointing to an odd element, then move to the next element by incrementing i and decrementing j.

Step 3: The resulting array will be the sorted array, with odd numbers appearing before even numbers and the relative order of odd and even numbers remaining the same as in the original array.

Time Complexity:

The time complexity of this solution is O(n) as we traverse the array only once. The space complexity is O(1) as we do not use any extra space.

Sort The Jumbled Numbers Solution Code

1