A friend of mine came across this question in an online Assessment of a company and asked me this question.
An array of integers is given and we have to (possibly) arrange the array such that no two consecutive numbers sum is divisible by 3.
Size of the array
n<=10^5
.If no such arrangement is possible then we have to return
Not Possible
.
I could think of greedily filling integers such that consecutive element sum if not divisible by 3 that will give an O(n^2)
solution (BUT I am not sure if greedily filling elements will give the solution here) or I could think of doing a (bruteforce) DFS
by looking all possible arrangements but that would be an exponential time solution and certainly won't work here for the given array size condition.
Is there any O(nlogn)
or O(n)
solution possible for this?
So, our answer is YES. To solve this problem, we will check its divisibility by 3. Divisibility by 3 − a number is divisible by 3 if the sum of its digits is divisible by 3.
Consecutive numbers are numbers that follow each other in order from the smallest number to the largest number. The difference between consecutive numbers is always fixed and it follows a pattern. For example 1, 2, 3 are the first three consecutive natural numbers.
Using the Formula(n / 2)(first number + last number) = sum, where n is the number of integers.
yes there exists O(n) solution:
x
will belong to bucket x mod 3
1
and 2
cannot be neighbors, same for elements from bucket 0
and 0
1
into the answer, followed by one element from bucket 0
and all elements from bucket 2
0
which we can put between two elements of bucket 1
or two element from bucket 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With