Count passing car pairs - GeeksforGeeks

27 Apr, 2021
A non-empty binary array A consisting of size N is given where,  
0 represents a car traveling east,
1 represents a car traveling west. 
The goal is to count passing cars. We say that a pair of cars (P, Q), where 0 <= P < Q < N, is passing when P is traveling to the east and Q is traveling to the west.Examples:  
Input  : arr[] = {0, 1, 0, 1, 1}
Output : 5
The 5 pairs are (A[0], A[1]), (A[0], A[3]), (A[0], A[4]),   
(A[2], A[3]) and (A[2], A[4]). Note that in all pairs
first element is 0, second element is 1 and index of
first element is smaller than index of second element.

Input  : arr[] = {1, 0, 0, 0, 1}
Output : 3

Input : arr[] = {0, 0, 1, 0, 0}
Output : 2
 
A simple solution is to use two nested loops. The outer loop searches for a 0, the inner loop counts a number of 1s after 0. Finally, we return the total count.  
C++
Java
Python3
C#
PHP
Javascript
// Simple C++ program to count passing cars#include<bits/stdc++.h>using namespace std; // Returns count of passing carsint getPassingCars(int A[], int n){    int result = 0;    for (int i=0; i<n-1; i++)    {       if (A[i] == 0)       {           for (int j=i+1; j<n; j++)               if (A[j])                 result++;       }    }    return result;} // Driver programint main(){    int A[] = {0, 1, 0, 1, 1};    int n = sizeof(A)/sizeof(A[0]);    cout << getPassingCars(A, n);    return 0;}
// Simple Java program to count passing carsclass GFG{ // Returns count of passing carsstatic int getPassingCars(int[] A, int n){    int result = 0;    for (int i = 0; i < n - 1; i++)    {    if (A[i] == 0)    {        for (int j = i + 1; j < n; j++)            if (A[j] == 1)                result++;    }    }    return result;} // Driver Codepublic static void main(String[] args){    int[] A = {0, 1, 0, 1, 1};    int n = A.length;    System.out.println(getPassingCars(A, n));}} // This code is contributed// by Code_Mech
# Simple Python 3 program to# count passing cars # Returns count of passing carsdef getPassingCars(A, n):    result = 0    for i in range(0, n - 1, 1):        if (A[i] == 0):            for j in range(i + 1, n, 1):                if (A[j]):                    result += 1             return result # Driver Codeif __name__ == '__main__':    A = [0, 1, 0, 1, 1]    n = len(A)    print(getPassingCars(A, n))     # This code is contributed by# Sanjit_Prasad
// Simple C# program to count passing carsusing System; class GFG{ // Returns count of passing carsstatic int getPassingCars(int[] A, int n){    int result = 0;    for (int i = 0; i < n - 1; i++)    {    if (A[i] == 0)    {        for (int j = i + 1; j < n; j++)            if (A[j] == 1)                result++;    }    }    return result;} // Driver Codepublic static void Main(){    int[] A = {0, 1, 0, 1, 1};    int n = A.Length;    Console.WriteLine(getPassingCars(A, n));}} // This code is contributed// by Akanksha Rai
<?php// Simple PHP program to count passing cars // Returns count of passing carsfunction getPassingCars($A, $n){    $result = 0;    for ($i = 0; $i < $n - 1; $i++)    {        if ($A[$i] == 0)        {            for ($j = $i + 1; $j < $n; $j++)                if ($A[$j])                    $result++;        }    }    return $result;}     // Driver Code    $A = array(0, 1, 0, 1, 1);    $n = sizeof($A);    echo getPassingCars($A, $n); // This code is contributed by m_kit?>
<script>     // Simple Javascript program    // to count passing cars         // Returns count of passing cars    function getPassingCars(A, n)    {        let result = 0;        for (let i = 0; i < n - 1; i++)        {          if (A[i] == 0)          {              for (let j = i + 1; j < n; j++)                  if (A[j] == 1)                      result++;          }        }        return result;    }         let A = [0, 1, 0, 1, 1];    let n = A.length;    document.write(getPassingCars(A, n));     </script>
Output:
5
Time Complexity : O(n2) Auxiliary Space : O(1) An efficient solution to traverse array from right, keep track of counts of 1s from the right. Whenever we see a 0, we increment the result by a count of 1s.  
C++
Java
Python3
C#
PHP
Javascript
// Efficient C++ program to count passing cars#include<bits/stdc++.h>using namespace std; // Returns count of passing carsint getPassingCars(int A[], int n){    // Initialize count of 1s from right    // and result    int countOne = 0, result = 0;    while (n >= 1)    {        if (A[n-1] == 1)            countOne++;        else            result += countOne;        n--;    }     return result;} // Driver programint main(){    int A[] = {0, 1, 0, 1, 1};    int n = sizeof(A)/sizeof(A[0]);    cout << getPassingCars(A, n);    return 0;}
// Efficient Java program to count passing carsclass GFG{     // Returns count of passing carsstatic int getPassingCars(int A[], int n){    // Initialize count of 1s from right    // and result    int countOne = 0, result = 0;    while (n >= 1)    {        if (A[n-1] == 1)            countOne++;        else            result += countOne;        n--;    }     return result;} // Driver codepublic static void main(String[] args){    int A[] = {0, 1, 0, 1, 1};    int n = A.length;    System.out.println(getPassingCars(A, n));}} // This code is contributed by Mukul Singh.
# Efficient Python3 program to# count passing cars # Returns count of passing carsdef getPassingCars(A, n):     # Initialize count of 1s    # from right and result    countOne = 0; result = 0    while n >= 1:        if A[n - 1] == 1:            countOne += 1        else:            result += countOne        n -= 1    return result # Driver codeA = [0, 1, 0, 1, 1]n = len(A)print(getPassingCars(A, n)) # This code is contributed# by Shrikant13
// Efficient C# program to// count passing carsusing System; class GFG{     // Returns count of passing carsstatic int getPassingCars(int []A, int n){    // Initialize count of 1s from right    // and result    int countOne = 0, result = 0;    while (n >= 1)    {        if (A[n - 1] == 1)            countOne++;        else            result += countOne;        n--;    }     return result;} // Driver codepublic static void Main(){    int []A = {0, 1, 0, 1, 1};    int n = A.Length;    Console.Write(getPassingCars(A, n));}} // This code is contributed// by Akanksha Rai
<?php// Efficient PHP program to count passing cars // Returns count of passing carsfunction getPassingCars($A, $n){    // Initialize count of 1s from right    // and result    $countOne = 0; $result = 0;    while ($n >= 1)    {        if ($A[$n-1] == 1)            $countOne++;        else            $result += $countOne;        $n--;    }     return $result;} // Driver Code$A = array(0, 1, 0, 1, 1);$n = sizeof($A);echo getPassingCars($A, $n); // This code is contributed// by Akanksha Rai?>
<script>    // Efficient Javascript program to count passing cars         // Returns count of passing cars    function getPassingCars(A, n)    {        // Initialize count of 1s from right        // and result        let countOne = 0, result = 0;        while (n >= 1)        {            if (A[n - 1] == 1)                countOne++;            else                result += countOne;            n--;        }         return result;    }         let A = [0, 1, 0, 1, 1];    let n = A.length;    document.write(getPassingCars(A, n));     </script>
Output: 
5
Time Complexity: O(n) Auxiliary Space: O(1)Reference : http://stackoverflow.com/questions/23774985/codility-passing-carThis article is contributed by Rakesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
jit_t
Sanjit_Prasad
Akanksha_Rai
shrikanth13
Code_Mech
divyeshrabadiya07
divyesh072019
binary-string
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Python | Using 2D arrays/lists the right way
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Queue | Set 1 (Introduction and Array Implementation)