Codility lessons

senduran

Ars Tribunus Militum
2,927
Subscriptor
I recently had to do a codility test for a job interview. Now I realise I need to brush up on some basics. They offer "lessons" which I've started going through, but they don't make for very good lessons because they only test you and don't provide examples of good answers. I've done the first 3 tests in the lesson set, and wondered if there were better implementations possible than what I came up with.

Let's discuss lesson 2: https://app.codility.com/programmers/lessons/2-arrays/ (you probably need a free account first)

For CyclicRotation it only cares about correctness, not performance, but is there a clever fast implementation that doesn't involve creating as many new arrays as requested rotations?

Here's my answer for OddOccurrencesInArray (written in Go):

Code:
func Solution(A []int) int {
    h := make(map[int]int)
    for _, n := range A {
        h[n]++
    }
    for n, c := range h {
        if c % 2 != 0 {
            return n
        }
    }
    return 0
}

They gave me 100% for correctness and performance ("Detected time complexity: O(N) or O(N*log(N))"). I thought this was the obvious "dumb" way and a bit icky, but couldn't think of anything cleverer. Can you?
 

tb12939

Ars Tribunus Militum
2,157
For CyclicRotation it only cares about correctness, not performance, but is there a clever fast implementation that doesn't involve creating as many new arrays as requested rotations?
You can rotate by multiple positions in a single split copy: Rather than last position -> first, you just do two / three / X positions to first two / three / X positions.

...for OddOccurrencesInArray...

They gave me 100% for correctness and performance ("Detected time complexity: O(N) or O(N*log(N))"). I thought this was the obvious "dumb" way and a bit icky, but couldn't think of anything cleverer. Can you?
XOR all the things :)

Each identical pair XORs to zero (net, even if separated), so at the end, the unpaired value remains.
 

senduran

Ars Tribunus Militum
2,927
Subscriptor
For CyclicRotation it only cares about correctness, not performance, but is there a clever fast implementation that doesn't involve creating as many new arrays as requested rotations?
You can rotate by multiple positions in a single split copy: Rather than last position -> first, you just do two / three / X positions to first two / three / X positions.

What do you mean by "split copy"? Is it possible to do this without creating a new array at all?

...for OddOccurrencesInArray...
XOR all the things :)

Each identical pair XORs to zero (net, even if separated), so at the end, the unpaired value remains.

Yes :) I never deal in those operations in real life so would never have thought of it, but the solution does look beautiful:

Code:
    v := A[0]
    for i := 1; i < len(A); i++ {
        v ^= A[i]
    }
    return v
 

senduran

Ars Tribunus Militum
2,927
Subscriptor
Here's my solution for lesson 3, TapeEquilibrium:

Code:
func Solution(A []int) int {
    f := make([]int, len(A)-1)
    f[0] = A[0]
    for i := 1; i < len(A) - 1; i++ {
        f[i] = A[i] + f[i-1]
    }
    
    r := make([]int, len(A)-1)
    r[len(A) - 2] = A[len(A) - 1]
    for i := len(A) - 2; i > 0; i-- {
        r[i-1] = A[i] + r[i]
    }
    
    min := 10000
    for i, fi := range f {
        var diff int
        if fi > r[i] {
            diff = fi - r[i]
        } else {
            diff = r[i] - fi
        }
        if diff < min {
            min = diff
        }
    }
    
    return min
}

Again it passes 100%, but again I feel it's a little clumsy. Is there a way to do it without going through the input array twice and creating 2 arrays?
 

tb12939

Ars Tribunus Militum
2,157
For CyclicRotation it only cares about correctness, not performance, but is there a clever fast implementation that doesn't involve creating as many new arrays as requested rotations?
You can rotate by multiple positions in a single split copy: Rather than last position -> first, you just do two / three / X positions to first two / three / X positions.

What do you mean by "split copy"? Is it possible to do this without creating a new array at all?
On phone so formatting limited...

Sorry, thought you meant an array per single position rotation. A split copy implements any rotation distance in one pass: given n elements and an r position rotation, copy r elements from source end to destination start, and n-r from source start to destination end.

Doing without a second array is doable, but likely slower in practice. Consider a one position rotation left: store the first position in a temp, copy each i+1 to i until n, store temp in the last position. This generalizes to any case where n and r are relatively prime by using indexes i mod n and i+r mod n. For the cases where there are common factors between n and r, you need to repeat the process with offsets similar to a shell sort - e.g if n is even and r is 2, do an even pass and an odd pass.
 

fitten

Ars Legatus Legionis
55,632
Subscriptor++
Just brainstorming... seems like you could have one extra array which stores the running total from the input array. One pass through the input array gives both the running totals and the total of the entire array (in the Nth location). Then one pass through the running totals array for any index (N-1) gives you the "sum of the first part" (the running total that's been precomputed) which you subtract from the overall total (either stored separately or found in running totals array at location N) to get the "sum of the second part", subtract those two and you get your "difference". Remember your smallest difference and return it.

You really don't even need the running totals array, to be honest... just make two passes of the input array (and no extra arrays)... the first is to find the total of all the array, then on the second pass through the input array you again calculate the running total and do the calculation above.
 

tb12939

Ars Tribunus Militum
2,157
Is there a way to do it without going through the input array twice and creating 2 arrays?
Yup, think so. Keep a running total from each end, advance the side with the lower total. Not tested due to phone 😀
Arg - didn't notice the possibility for negative values in the input. That ruins the 'incremental from each end' one-pass approach (which i think works, but only if the numbers are non-negative). Given negative inputs, i don't see any way to avoid the need to calculate the total in one pass, and find the lowest absolute difference i.e. abs(total - runningTotal*2) in a second pass, as suggested by fitten.