<script>
// Javascript program to implement the above approach
let maxN = 100;
// Stores nodes value of the Tree
let Tree = new Array(4 * maxN);
// Function to build segment tree
function build(arr, index, s, e)
{
// Base Case
if (s == e)
Tree[index] = arr[s];
else
{
// Find the value of mid
let m = parseInt((s + e) / 2, 10);
// Update for left subtree
build(arr, 2 * index, s, m);
// Update for right subtree
build(arr, 2 * index + 1,
m + 1, e);
// Update the value at the
// current index
Tree[index]
= Math.max(Tree[2 * index],
Tree[2 * index + 1]);
}
}
// Function for finding the index
// of the first element at least x
function atleast_x(index, s, e, ql, qr, x)
{
// If current range does
// not lie in query range
if (ql > e || qr < s)
return -1;
// If current range is inside
// of query range
if (s <= ql && e <= qr) {
// Maximum value in this
// range is less than x
if (Tree[index] < x)
return -1;
// Finding index of first
// value in this range
while (s != e) {
let m = parseInt((s + e) / 2, 10);
// Update the value of
// the minimum index
if (Tree[2 * index] >= x) {
e = m;
index = 2 * index;
}
else {
s = m + 1;
index = 2 * index + 1;
}
}
return s;
}
// Find mid of the current range
let m = parseInt((s + e) / 2, 10);
// Left subtree
let val = atleast_x(2 * index, s,
m, ql, qr, x);
if (val != -1)
return val;
// If it does not lie in
// left subtree
return atleast_x(2 * index + 1, m + 1,
e, ql, qr, x);
}
// Function for updating segment tree
function update(index, s, e, new_val, pos)
{
// Update the value, we
// reached leaf node
if (s == e)
Tree[index] = new_val;
else
{
// Find the mid
let m = parseInt((s + e) / 2, 10);
if (pos <= m)
{
// If pos lies in the
// left subtree
update(2 * index, s, m,
new_val, pos);
}
else
{
// pos lies in the
// right subtree
update(2 * index + 1,
m + 1, e,
new_val, pos);
}
// Update the maximum value
// in the range
Tree[index]
= Math.max(Tree[2 * index],
Tree[2 * index + 1]);
}
}
// Function to print the answer
// for the given queries
function printAnswer(arr, n)
{
// Build segment tree
build(arr, 1, 0, n - 1);
// Find index of first value
// atleast 2 in range [0, n-1]
document.write(atleast_x(1, 0, n - 1, 0, n - 1, 2) + "</br>");
// Update value at index 2 to 5
arr[2] = 5;
update(1, 0, n - 1, 5, 2);
// Find index of first value
// atleast 4 in range [0, n-1]
document.write(atleast_x(1, 0, n - 1, 0, n - 1, 4) + "</br>");
// Find index of first value
// atleast 0 in range [0, n-1]
document.write(atleast_x(1, 0, n - 1, 0, n - 1, 0) + "</br>");
}
let arr = [ 1, 3, 2, 4, 6 ];
let N = arr.length;
// Function Call
printAnswer(arr, N);
// This code is contributed by decode2207.
</script>