• 25.4%

https://leetcode.com/problems/wiggle-sort-ii/?tab=Description

Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]….

Note:

You may assume all input has valid answer.

Can you do it in O(n) time and/or in-place with O(1) extra space?

https://discuss.leetcode.com/topic/32929/o-n-o-1-after-median-virtual-indexing

O(n)+O(1) after median — Virtual Indexing

This post is mainly about what I call “virtual indexing” technique (I’m sure I’m not the first who came up with this, but I couldn’t find anything about it, so I made up a name as well. If you know better, let me know).

Solution

Explanation

First I find a median using nth_element. That only guarantees O(n) average time complexity and I don’t know about space complexity. I might write this myself using O(n) time and O(1) space, but that’s not what I want to show here.

This post is about what comes after that. We can use three-way partitioning to arrange the numbers so that those larger than the median come first, then those equal to the median come next, and then those smaller than the median come last.

Ordinarily, you’d then use one more phase to bring the numbers to their final positions to reach the overall wiggle-property. But I don’t know a nice O(1) space way for this. Instead, I embed this right into the partitioning algorithm. That algorithm simply works with indexes 0 to n-1 as usual, but sneaky as I am, I rewire those indexes where I want the numbers to actually end up. The partitioning-algorithm doesn’t even know that I’m doing that, it just works like normal (it just uses A(x) instead of nums[x]).

Let’s say nums is [10,11,…,19]. Then after nth_element and ordinary partitioning, we might have this (15 is my median):

I rewire it so that the first spot has index 5, the second spot has index 0, etc, so that I might get this instead:

And 11 18 14 17 10 19 13 16 12 15 is perfectly wiggly. And the whole partitioning-to-wiggly-arrangement (everything after finding the median) only takes O(n) time and O(1) space.

If the above description is unclear, maybe this explicit listing helps:

Props to apolloydy’s solution, I knew the partitioning algorithm already but I didn’t know the name. And apolloydy’s idea to partition to reverse order happened to make the index rewiring simpler.

https://discuss.leetcode.com/topic/41464/step-by-step-explanation-of-index-mapping-in-java

Step by step explanation of index mapping in Java

The virtual index idea in the post https://leetcode.com/discuss/77133/o-n-o-1-after-median-virtual-indexing
is very brilliant! However, it takes me a while to understand why and how it works. There is no ‘nth_element’ in Java, but you can use ‘findKthLargest’ function from “https://leetcode.com/problems/kth-largest-element-in-an-array/" to get the median element in average O(n) time and O(1) space.

Assume your original array is {6,13,5,4,5,2}. After you get median element, the ‘nums’ is partially sorted such that the first half is larger or equal to the median, the second half is smaller or equal to the median, i.e

In the post https://leetcode.com/discuss/76965/3-lines-python-with-explanation-proof, we have learned that , to get wiggle sort, you want to put the number in the following way such that

(1) elements smaller than the ‘median’ are put into the last even slots

(2) elements larger than the ‘median’ are put into the first odd slots

(3) the medians are put into the remaining slots.

M - Median, S-Small, L-Large. In this example, we want to put {13, 6, 5} in index 1,3,5 and {5,4,2} in index {0,2,4}

The index mapping, (1 + 2 * index) % (n | 1) combined with ‘Color sort’, will do the job.

After selecting the median element, which is 5 in this example, we continue as the following

The code is the following:

https://discuss.leetcode.com/topic/32861/3-lines-python-with-explanation-proof

3 lines Python, with Explanation / Proof

Solution

Roughly speaking I put the smaller half of the numbers on the even indexes and the larger half on the odd indexes.

Alternative, maybe nicer, maybe not:

Explanation / Proof

I put the smaller half of the numbers on the even indexes and the larger half on the odd indexes, both from right to left:

I want:

• Odd-index numbers are larger than their neighbors.

Since I put the larger numbers on the odd indexes, clearly I already have:

• Odd-index numbers are larger than or equal to their neighbors.

Could they be “equal to”? That would require some number M to appear both in the smaller and the larger half. It would be the largest in the smaller half and the smallest in the larger half. Examples again, where S means some number smaller than M and L means some number larger than M.

You can see the two M are quite far apart. Of course M could appear more than just twice, for example:

You can see that with seven numbers, three M are no problem. And with eight numbers, four M are no problem. Should be easy to see that in general, with n numbers, floor(n/2) times M is no problem. Now, if there were more M than that, then my method would fail. But… it would also be impossible:

• If n is even, then having more than n/2 times the same number clearly is unsolvable, because you’d have to put two of them next to each other, no matter how you arrange them.
• If n is odd, then the only way to successfully arrange a number appearing more than floor(n/2) times is if it appears exactly floor(n/2)+1 times and you put them on all the even indexes. And to have the wiggle-property, all the other numbers would have to be larger. But then we wouldn’t have an M in both the smaller and the larger half.

So if the input has a valid answer at all, then my code will find one.

https://discuss.leetcode.com/topic/32920/o-n-time-o-1-space-solution-with-detail-explanations

O(n)-time O(1)-space solution with detail explanations

Methodology:

Idea 1.

As @whnzinc pointed out in this thread, all elements in nums can be classified into three categories:

(1) Larger than the median;

(2) Equal to the median;

(3) Smaller than the median.

Note that it’s possible to find the median within O(n)-time and O(1)-space.

Note: We can use nth_element to find the median, but it’s not O(n)-time and O(1)-space. For the sake of simplicity, I might use nth_element as well.

Idea 2.

As @StefanPochmann pointed out in this thread, we can arrange the elements in the three categories in a deterministic way.

(1) Elements that are larger than the median: we can put them in the first few odd slots;

(2) Elements that are smaller than the median: we can put them in the last few even slots;

(3) Elements that equal the median: we can put them in the remaining slots.

Update: According to @StefanPochmann’s thread, we can use a one-pass three-way partition to rearrange all elements. His idea is to re-map the indices into its destined indices, odd indices first and even indices follow.

Example:

(its reverse mapping is)

In order to achieve this, we can use a function alike

where (n | 1) calculates the nearest odd that is not less than n.

Complexities: (On the condition that finding median is O(n)-time and O(1)-space)

• Time: O(n)

• Space: O(1)

C++ (Updated, 44ms):

https://discuss.leetcode.com/topic/32882/short-simple-c

Short simple C++

Sort and then write the smaller half of the numbers on the even indexes and the larger half of the numbers on the odd indexes, both from the back. Example:

So write nums from the back, interweaving sorted[0..4] (indexed by j) and sorted[5..9] (indexed by k).

For more explanation/proof, see my equivalent Python solution.

https://discuss.leetcode.com/topic/32923/simple-modulo-solution

Simple modulo solution

Once again I sort and then spread the numbers like in this example with nums=[0,1,…,9]:

Just write the numbers 9, 8, 7, etc at indexes 1, 3, 5, etc. Use modulo to wrap around for the second round (the even indexes).

Python

C++

Or: