Arrange an integer array such that no two consecutive numbers sum is divisible by 3
yes there exists O(n) solution:
- First divide all element into 3 buckets, element
x
will belong to bucketx mod 3
- Now we can use greedy strategy: notice that elements from buckets
1
and2
cannot be neighbors, same for elements from bucket0
and0
- We can put all elements from bucket
1
into the answer, followed by one element from bucket0
and all elements from bucket2
- Now all that's left is some elements from bucket
0
which we can put between two elements of bucket1
or two element from bucket2
- Of course there are some corner cases for which solution is impossible