# Passing Cars – Codility 100% Correct Javascript Solution

The Passing Cars challenge takes a step back in difficulty but it’s still a fun problem to solve.

It can be done with O(N) complexity and it’s fairly easy. Basically we have to realize that when a car travelling East meets a car travelling West, it will pair with all the previous cars travelling West as well but not with the ones that come after it in the array. So, the simplest way to keep track is to iterate through the array and if the current element is a car travelling west, we add it to a counter, while if it is a car travelling east, we add the current counter to the result sum. The current counter will in this case represent all the pairs that car travelling east will represent.

At the end we just return the result variable. Here is the javascript solution:

``````function solution(A) {
let sum = 0
let result = 0
for (let i = A.length-1; i >= 0; i--){
if (A[i] === 1) {
sum++
} else {
result += sum
}
if (result > 1000000000) {
result = -1
break
}

}
return(result)

}``````

And here is the report. Tell me in the comments if you found a better, quicker solution!