Find common elements in three sorted arrays | This function prints common elements in ar1 ; Initialize starting indexes for ar1 [ ] , ar2 [ ] and ar3 [ ] ; Declare three variables prev1 , prev2 , prev3 to track previous element ; Initialize prev1 , prev2 , prev3 with INT_MIN ; Iterate through three arrays while all arrays have elements ; If ar1 [ i ] = prev1 and i < n1 , keep incrementing i ; If ar2 [ j ] = prev2 and j < n2 , keep incrementing j ; If ar3 [ k ] = prev3 and k < n3 , keep incrementing k ; If x = y and y = z , print any of them , update prev1 prev2 , prev3 and move ahead in each array ; If x < y , update prev1 and increment i ; If y < z , update prev2 and increment j ; We reach here when x > y and z < y , i . e . , z is smallest update prev3 and imcrement k ; Driver code
function findCommon ( ar1 , ar2 , ar3 , n1 , n2 , n3 ) { var i = 0 , j = 0 , k = 0 ; var prev1 , prev2 , prev3 ; prev1 = prev2 = prev3 = - 1000000000 ; while ( i < n1 && j < n2 && k < n3 ) { while ( ar1 [ i ] == prev1 && i < n1 ) i ++ ; while ( ar2 [ j ] == prev2 && j < n2 ) j ++ ; while ( ar3 [ k ] == prev3 && k < n3 ) k ++ ; if ( ar1 [ i ] == ar2 [ j ] && ar2 [ j ] == ar3 [ k ] ) { document . write ( ar1 [ i ] + " " ) ; prev1 = ar1 [ i ] ; prev2 = ar2 [ j ] ; prev3 = ar3 [ k ] ; i ++ ; j ++ ; k ++ ; } else if ( ar1 [ i ] < ar2 [ j ] ) { prev1 = ar1 [ i ] ; i ++ ; } else if ( ar2 [ j ] < ar3 [ k ] ) { prev2 = ar2 [ j ] ; j ++ ; } else { prev3 = ar3 [ k ] ; k ++ ; } } } var ar1 = [ 1 , 5 , 10 , 20 , 40 , 80 , 80 ] ; var ar2 = [ 6 , 7 , 20 , 80 , 80 , 100 ] ; var ar3 = [ 3 , 4 , 15 , 20 , 30 , 70 , 80 , 80 , 120 ] ; var n1 = ar1 . length ; var n2 = ar2 . length ; var n3 = ar3 . length ; document . write ( " " ) ; findCommon ( ar1 , ar2 , ar3 , n1 , n2 , n3 ) ;