let lower_bound arr x =
  let lo = ref 0 and hi = ref (Array.length arr) in
  while !lo < !hi do
    let mid = (!lo + !hi) / 2 in
    if arr.(mid) < x then lo := mid + 1
    else hi := mid
  done;
  !lo

let upper_bound arr x =
  let lo = ref 0 and hi = ref (Array.length arr) in
  while !lo < !hi do
    let mid = (!lo + !hi) / 2 in
    if arr.(mid) <= x then lo := mid + 1
    else hi := mid
  done;
  !lo

;;

let a = [| 1; 2; 2; 3; 3; 3; 5; 7; 9 |] in
let cnt3 = upper_bound a 3 - lower_bound a 3 in
let cnt2 = upper_bound a 2 - lower_bound a 2 in
let cnt5 = upper_bound a 5 - lower_bound a 5 in
let cnt9 = upper_bound a 9 - lower_bound a 9 in
let cnt4 = upper_bound a 4 - lower_bound a 4 in
cnt3 * 1000 + cnt2 * 100 + cnt5 * 10 + cnt9 + cnt4
