Queries forType of Subarray and Update

Last Updated : 23 Aug, 2026

Given an array arr[] of n integers and a 2D array queries[][] of size q × 3, process each query in the given order. Each query is of one of the following two types:

  • [1, l, r]: Update the value of arr[l] to r ( where 1 â‰Ī l, r â‰Ī n).
  • [2, l, r]: Determine the order of the subarray arr[l...r] (both indices inclusive).

For each query of type 2, return:

  • 0 if the subarray is non-decreasing.
  • 1 if the subarray is non-increasing.
  • -1 if all elements in the subarray are equal (i.e., it is both non-decreasing and non-increasing).
  • -1 if the subarray is neither non-decreasing nor non-increasing.

Return an array containing the results of all queries of type 2 in the order they appear.

Examples:

Input: arr[] = [1, 5, 7, 4, 3, 5, 9], queries[][] = [[2, 1, 3], [1, 7, 4], [2, 6, 7]]
Output: [0, 1]
Explanation: Query [2, 1, 3]: Subarray = [1, 5, 7], which is non-decreasing. Output = 0.
Query [1, 7, 4]: Update the 7th element to 4. Array becomes [1, 5, 7, 4, 3, 5, 4].
Query [2, 6, 7]: Subarray = [5, 4], which is non-increasing. Output = 1.

Input: arr[] = [4, 4, 4, 4], queries[][] = [[2, 1, 4], [1, 2, 5], [2, 1, 2]]
Output: [-1, 0]
Explanation: Query [2, 1, 4]: Subarray = [4, 4, 4, 4], which is both non-decreasing and non-increasing. Output = -1.
Query [1, 2, 5]: Update the 2nd element to 5. Array becomes [4, 5, 4, 4].
Query [2, 1, 2]: Subarray = [4, 5], which is non-decreasing. Output = 0.

Try It Yourself
redirect icon

[Naive Approach] Check the Subarray Directly - O(n) Time and O(1) Space

The idea is to traverse the given subarray and compare every pair of adjacent elements. Maintain two flags to check whether the subarray is non-decreasing or non-increasing, and use them to determine the required result.

Working of Approach:

  • For a type-1 query, update arr[l] with the value r.
  • For a type-2 query, traverse the subarray from l to r.
  • If arr[i] > arr[i + 1], it is not non-decreasing.
  • If arr[i] < arr[i + 1], it is not non-increasing.
  • Return -1 if both conditions hold or neither holds; otherwise return 0 or 1.
C++
#include <bits/stdc++.h>
using namespace std;

vector<int> processQueries(vector<int> &arr, vector<vector<int>> &queries)
{

    vector<int> res;

    for (auto q : queries)
    {
        int type = q[0];
        int A = q[1] - 1;
        int B = q[2];

        // Type 1 query: update the value at index A.
        if (type == 1)
        {
            arr[A] = B;
            continue;
        }

        bool isIncreasing = true;
        bool isDecreasing = true;

        // Check the ordering of the subarray.
        for (int i = A; i < B - 1; i++)
        {
            if (arr[i] > arr[i + 1])
                isIncreasing = false;

            if (arr[i] < arr[i + 1])
                isDecreasing = false;
        }

        // All elements are equal.
        if (isIncreasing && isDecreasing)
            res.push_back(-1);

        // Subarray is non-decreasing.
        else if (isIncreasing)
            res.push_back(0);

        // Subarray is non-increasing.
        else if (isDecreasing)
            res.push_back(1);

        // Subarray is neither.
        else
            res.push_back(-1);
    }

    return res;
}

int main()
{
    vector<int> nums = {1, 5, 7, 4, 3, 5, 9};

    vector<vector<int>> Queries = {{2, 1, 3}, {1, 7, 4}, {2, 6, 7}};

    vector<int> ans = processQueries(nums, Queries);

    // Print the result of all type-2 queries.
    cout << "[";

    for (int i = 0; i < ans.size(); i++)
    {
        if (i > 0)
            cout << ", ";

        cout << ans[i];
    }

    cout << "]";

    return 0;
}
Java
import java.util.ArrayList;
import java.util.List;

public class GFG {
    public static ArrayList<Integer>
    processQueries(int[] arr, int[][] queries)
    {
        ArrayList<Integer> res = new ArrayList<>();

        for (int[] q : queries) {
            int type = q[0];
            int A = q[1] - 1;
            int B = q[2];

            // Type 1 query: update the value at index A.
            if (type == 1) {
                arr[A] = B;
                continue;
            }

            boolean isIncreasing = true;
            boolean isDecreasing = true;

            // Check the ordering of the subarray.
            for (int i = A; i < B - 1; i++) {
                if (arr[i] > arr[i + 1])
                    isIncreasing = false;

                if (arr[i] < arr[i + 1])
                    isDecreasing = false;
            }

            // All elements are equal.
            if (isIncreasing && isDecreasing)
                res.add(-1);

            // Subarray is non-decreasing.
            else if (isIncreasing)
                res.add(0);

            // Subarray is non-increasing.
            else if (isDecreasing)
                res.add(1);

            // Subarray is neither.
            else
                res.add(-1);
        }

        return res;
    }

    public static void main(String[] args)
    {
        int[] nums = { 1, 5, 7, 4, 3, 5, 9 };
        int[][] Queries
            = { { 2, 1, 3 }, { 1, 7, 4 }, { 2, 6, 7 } };

        ArrayList<Integer> ans = processQueries(nums, Queries);

        // Print the result of all type-2 queries.
        System.out.print("[");

        for (int i = 0; i < ans.size(); i++) {
            if (i > 0)
                System.out.print(", ");

            System.out.print(ans.get(i));
        }

        System.out.print("]");
    }
}
Python
def processQueries(arr, queries):

    res = []

    for q in queries:
        type = q[0]
        A = q[1] - 1
        B = q[2]

        # Type 1 query: update the value at index A.
        if type == 1:
            arr[A] = B
            continue

        isIncreasing = True
        isDecreasing = True

        # Check the ordering of the subarray.
        for i in range(A, B - 1):
            if arr[i] > arr[i + 1]:
                isIncreasing = False

            if arr[i] < arr[i + 1]:
                isDecreasing = False

        # All elements are equal.
        if isIncreasing and isDecreasing:
            res.append(-1)

        # Subarray is non-decreasing.
        elif isIncreasing:
            res.append(0)

        # Subarray is non-increasing.
        elif isDecreasing:
            res.append(1)

        # Subarray is neither.
        else:
            res.append(-1)

    return res


if __name__ == '__main__':
    nums = [1, 5, 7, 4, 3, 5, 9]
    Queries = [[2, 1, 3], [1, 7, 4], [2, 6, 7]]

    ans = processQueries(nums, Queries)

    # Print the result of all type-2 queries.
    print('[', end='')

    for i in range(len(ans)):
        if i > 0:
            print(', ', end='')

        print(ans[i], end='')

    print(']')
C#
using System;
using System.Collections.Generic;

public class GFG {
    public static List<int> processQueries(int[] arr,
                                           int[][] queries)
    {
        List<int> res = new List<int>();

        foreach(var q in queries)
        {
            int type = q[0];
            int A = q[1] - 1;
            int B = q[2];

            // Type 1 query: update the value at index A.
            if (type == 1) {
                arr[A] = B;
                continue;
            }

            bool isIncreasing = true;
            bool isDecreasing = true;

            // Check the ordering of the subarray.
            for (int i = A; i < B - 1; i++) {
                if (arr[i] > arr[i + 1])
                    isIncreasing = false;

                if (arr[i] < arr[i + 1])
                    isDecreasing = false;
            }

            // All elements are equal.
            if (isIncreasing && isDecreasing)
                res.Add(-1);

            // Subarray is non-decreasing.
            else if (isIncreasing)
                res.Add(0);

            // Subarray is non-increasing.
            else if (isDecreasing)
                res.Add(1);

            // Subarray is neither.
            else
                res.Add(-1);
        }

        return res;
    }

    public static void Main()
    {
        int[] nums = { 1, 5, 7, 4, 3, 5, 9 };
        int[][] Queries
            = new int[][] { new int[] { 2, 1, 3 },
                            new int[] { 1, 7, 4 },
                            new int[] { 2, 6, 7 } };

        List<int> ans = processQueries(nums, Queries);

        // Print the result of all type-2 queries.
        Console.Write("[");

        for (int i = 0; i < ans.Count; i++) {
            if (i > 0)
                Console.Write(", ");

            Console.Write(ans[i]);
        }

        Console.Write("]");
    }
}
JavaScript
function processQueries(arr, queries)
{

    let res = [];

    for (let q of queries) {
        let type = q[0];
        let A = q[1] - 1;
        let B = q[2];

        // Type 1 query: update the value at index A.
        if (type == 1) {
            arr[A] = B;
            continue;
        }

        let isIncreasing = true;
        let isDecreasing = true;

        // Check the ordering of the subarray.
        for (let i = A; i < B - 1; i++) {
            if (arr[i] > arr[i + 1])
                isIncreasing = false;

            if (arr[i] < arr[i + 1])
                isDecreasing = false;
        }

        // All elements are equal.
        if (isIncreasing && isDecreasing)
            res.push(-1);

        // Subarray is non-decreasing.
        else if (isIncreasing)
            res.push(0);

        // Subarray is non-increasing.
        else if (isDecreasing)
            res.push(1);

        // Subarray is neither.
        else
            res.push(-1);
    }

    return res;
}

// Driver Code
let nums = [ 1, 5, 7, 4, 3, 5, 9 ];
let Queries = [ [ 2, 1, 3 ], [ 1, 7, 4 ], [ 2, 6, 7 ] ];

let ans = processQueries(nums, Queries);

// Print the result of all type-2 queries.
console.log("[");

for (let i = 0; i < ans.length; i++) {
    if (i > 0)
        console.log(", ", ans[i]);
    else
        console.log(ans[i]);
}

console.log("]");

Output
[0, 1]

[Expected Approach] Using Fenwick Tree (BIT) - O(log n) Time and O(n) Space

The idea is to use two Fenwick Trees to store positions where adjacent elements violate non-decreasing or non-increasing order.

For each query, count these violations in the given range. During an update, only the two adjacent pairs around the changed index need to be updated.

Working of Approach:

  • inc stores positions where arr[i-1] > arr[i], which means non-decreasing order is violated.
  • dec stores positions where arr[i-1] < arr[i], which means non-increasing order is violated.
  • For range [l, r], query positions [l, r-1] to count all adjacent violations.
  • If both counts are 0, all elements are equal, so return -1.
  • If badInc == 0, return 0; if badDec == 0, return 1; otherwise return -1.
  • During an update, remove the old contribution and add the new contribution for the at most two affected adjacent pairs.

Let us understand with an example:
Input: arr[] = [1, 5, 7, 4, 3, 5, 9], queries = [[2, 1, 3], [1, 7, 4], [2, 6, 7]]

  • First, build two Fenwick Trees: inc stores positions where arr[i-1] > arr[i], while dec stores positions where arr[i-1] < arr[i].
  • For the initial array, inc stores the decreasing violations at 7 > 4 and 4 > 3, while dec stores the increasing adjacent pairs.
  • During an update, only the adjacent pairs involving the updated index are removed and added again.

Query 1: [2, 1, 3]

  • This is a type-2 query, so we check the range [1, 3].
  • The subarray is [1, 5, 7].
  • There is no violation of non-decreasing order, so badInc = 0.
  • Therefore, the subarray is non-decreasing and the answer is 0.

Query 2: [1, 7, 4]

  • This is a type-1 update query.
  • Convert index 7 to 0-based index 6.
  • Update arr[6] from 9 to 4.
  • The array becomes [1, 5, 7, 4, 3, 5, 4].
  • The Fenwick Trees are updated for the adjacent pairs involving index 6.

Query 3: [2, 6, 7]

  • This is a type-2 query for the range [6, 7].
  • The subarray is [5, 4].
  • Since 5 > 4, there is a violation of non-decreasing order, so badInc > 0.
  • There is no violation of non-increasing order, so badDec = 0.
  • Therefore, the subarray is non-increasing and the answer is 1.

Final Output: [0, 1].

C++
#include <bits/stdc++.h>
using namespace std;

class BIT
{
  public:
    int n;
    vector<int> bit;

    BIT(int sz)
    {
        n = sz;
        bit.assign(n + 2, 0);
    }

    void add(int idx, int val)
    {
        while (idx <= n)
        {
            bit[idx] += val;
            idx += idx & -idx;
        }
    }

    int sum(int idx)
    {
        int res = 0;
        while (idx > 0)
        {
            res += bit[idx];
            idx -= idx & -idx;
        }
        return res;
    }

    int query(int l, int r)
    {
        if (l > r)
            return 0;
        return sum(r) - sum(l - 1);
    }
};

vector<int> processQueries(vector<int> &arr, vector<vector<int>> &queries)
{
    int n = arr.size();

    BIT inc(n), dec(n);

    // Build Fenwick Trees for increasing and decreasing violations.
    for (int i = 1; i < n; i++)
    {
        if (arr[i - 1] > arr[i])
            inc.add(i, 1);
        if (arr[i - 1] < arr[i])
            dec.add(i, 1);
    }

    vector<int> ans;

    for (auto &q : queries)
    {

        if (q[0] == 1)
        {

            int idx = q[1] - 1;
            int val = q[2];

            // Remove the contribution of adjacent pairs before updating.
            if (idx > 0)
            {
                inc.add(idx, -(arr[idx - 1] > arr[idx]));
                dec.add(idx, -(arr[idx - 1] < arr[idx]));
            }

            if (idx + 1 < n)
            {
                inc.add(idx + 1, -(arr[idx] > arr[idx + 1]));
                dec.add(idx + 1, -(arr[idx] < arr[idx + 1]));
            }

            arr[idx] = val;

            // Add the updated contribution of adjacent pairs.
            if (idx > 0)
            {
                inc.add(idx, (arr[idx - 1] > arr[idx]));
                dec.add(idx, (arr[idx - 1] < arr[idx]));
            }

            if (idx + 1 < n)
            {
                inc.add(idx + 1, (arr[idx] > arr[idx + 1]));
                dec.add(idx + 1, (arr[idx] < arr[idx + 1]));
            }
        }
        else
        {

            int l = q[1];
            int r = q[2];

            // Count violations in the queried range.
            int badInc = inc.query(l, r - 1);
            int badDec = dec.query(l, r - 1);

            // Determine the order of the subarray.
            if (badInc == 0 && badDec == 0)
                ans.push_back(-1);
            else if (badInc == 0)
                ans.push_back(0);
            else if (badDec == 0)
                ans.push_back(1);
            else
                ans.push_back(-1);
        }
    }

    return ans;
}

int main()
{
    vector<int> nums = {1, 5, 7, 4, 3, 5, 9};

    vector<vector<int>> Queries = {{2, 1, 3}, {1, 7, 4}, {2, 6, 7}};

    vector<int> ans = processQueries(nums, Queries);

    // Print the result of all type-2 queries.
    cout << "[";

    for (int i = 0; i < ans.size(); i++)
    {
        if (i > 0)
            cout << ", ";

        cout << ans[i];
    }

    cout << "]";

    return 0;
}
Java
import java.util.*;

class BIT {
    int n;
    int[] bit;

    BIT(int sz)
    {
        n = sz;
        bit = new int[n + 2];
    }

    void add(int idx, int val)
    {
        while (idx <= n) {
            bit[idx] += val;
            idx += idx & -idx;
        }
    }

    int sum(int idx)
    {
        int res = 0;

        while (idx > 0) {
            res += bit[idx];
            idx -= idx & -idx;
        }

        return res;
    }

    int query(int l, int r)
    {
        if (l > r)
            return 0;

        return sum(r) - sum(l - 1);
    }
}

class GFG {

    public ArrayList<Integer> processQueries(int[] arr, int[][] queries)
    {

        int n = arr.length;

        BIT inc = new BIT(n);
        BIT dec = new BIT(n);

        // Build Fenwick Trees for increasing and decreasing
        // violations.
        for (int i = 1; i < n; i++) {

            if (arr[i - 1] > arr[i])
                inc.add(i, 1);

            if (arr[i - 1] < arr[i])
                dec.add(i, 1);
        }

        ArrayList<Integer> result = new ArrayList<>();

        for (int[] q : queries) {

            if (q[0] == 1) {

                int idx = q[1] - 1;
                int val = q[2];

                // Remove old contribution of adjacent
                // pairs.
                if (idx > 0) {

                    inc.add(
                        idx,
                        -(arr[idx - 1] > arr[idx] ? 1 : 0));

                    dec.add(
                        idx,
                        -(arr[idx - 1] < arr[idx]? 1 : 0));
                }

                if (idx + 1 < n) {

                    inc.add(
                        idx + 1,
                        -(arr[idx] > arr[idx + 1]? 1 : 0));

                    dec.add(
                        idx + 1,
                        -(arr[idx] < arr[idx + 1]? 1 : 0));
                }

                // Update the array.
                arr[idx] = val;

                // Add new contribution of adjacent pairs.
                if (idx > 0) {

                    inc.add(idx, arr[idx - 1] > arr[idx]
                                     ? 1
                                     : 0);

                    dec.add(idx, arr[idx - 1] < arr[idx]
                                     ? 1
                                     : 0);
                }

                if (idx + 1 < n) {

                    inc.add(idx + 1, arr[idx] > arr[idx + 1]
                                         ? 1
                                         : 0);

                    dec.add(idx + 1, arr[idx] < arr[idx + 1]
                                         ? 1
                                         : 0);
                }
            }
            else {

                int l = q[1];
                int r = q[2];

                // Count violations in the queried range.
                int badInc = inc.query(l, r - 1);
                int badDec = dec.query(l, r - 1);

                // Determine the order of the subarray.
                if (badInc == 0 && badDec == 0)
                    result.add(-1);
                else if (badInc == 0)
                    result.add(0);
                else if (badDec == 0)
                    result.add(1);
                else
                    result.add(-1);
            }
        }

        return result;
    }

    public static void main(String[] args)
    {

        int[] nums = { 1, 5, 7, 4, 3, 5, 9 };

        int[][] Queries
            = { { 2, 1, 3 }, { 1, 7, 4 }, { 2, 6, 7 } };

        GFG obj = new GFG();

        ArrayList<Integer> ans = obj.processQueries(nums, Queries);

        // Print the result.
        System.out.print("[");

        for (int i = 0; i < ans.size(); i++) {

            if (i > 0)
                System.out.print(", ");

            System.out.print(ans.get(i));
        }

        System.out.println("]");
    }
}
Python
class BIT:

    def __init__(self, sz):
        self.n = sz
        self.bit = [0] * (self.n + 2)

    def add(self, idx, val):
        while idx <= self.n:
            self.bit[idx] += val
            idx += idx & -idx

    def sum(self, idx):
        res = 0

        while idx > 0:
            res += self.bit[idx]
            idx -= idx & -idx

        return res

    def query(self, l, r):
        if l > r:
            return 0

        return self.sum(r) - self.sum(l - 1)


def processQueries(arr, queries):

    n = len(arr)

    inc = BIT(n)
    dec = BIT(n)

    # Build Fenwick Trees for increasing and decreasing violations.
    for i in range(1, n):

        if arr[i - 1] > arr[i]:
            inc.add(i, 1)

        if arr[i - 1] < arr[i]:
            dec.add(i, 1)

    ans = []

    for q in queries:

        if q[0] == 1:

            idx = q[1] - 1
            val = q[2]

            # Remove old contribution of adjacent pairs.
            if idx > 0:
                inc.add(idx, -(arr[idx - 1] > arr[idx]))
                dec.add(idx, -(arr[idx - 1] < arr[idx]))

            if idx + 1 < n:
                inc.add(idx + 1, -(arr[idx] > arr[idx + 1]))
                dec.add(idx + 1, -(arr[idx] < arr[idx + 1]))

            arr[idx] = val

            # Add new contribution of adjacent pairs.
            if idx > 0:
                inc.add(idx, arr[idx - 1] > arr[idx])
                dec.add(idx, arr[idx - 1] < arr[idx])

            if idx + 1 < n:
                inc.add(idx + 1, arr[idx] > arr[idx + 1])
                dec.add(idx + 1, arr[idx] < arr[idx + 1])

        else:

            l = q[1]
            r = q[2]

            # Count violations in the queried range.
            badInc = inc.query(l, r - 1)
            badDec = dec.query(l, r - 1)

            # Determine the order of the subarray.
            if badInc == 0 and badDec == 0:
                ans.append(-1)
            elif badInc == 0:
                ans.append(0)
            elif badDec == 0:
                ans.append(1)
            else:
                ans.append(-1)

    return ans


if __name__ == "__main__":

    nums = [1, 5, 7, 4, 3, 5, 9]

    Queries = [
        [2, 1, 3],
        [1, 7, 4],
        [2, 6, 7]
    ]

    ans = processQueries(nums, Queries)

    print(ans)
C#
using System;
using System.Collections.Generic;

class BIT {
    public int n;
    public int[] bit;

    public BIT(int sz)
    {
        n = sz;
        bit = new int[n + 2];
    }

    public void Add(int idx, int val)
    {
        while (idx <= n) {
            bit[idx] += val;
            idx += idx & -idx;
        }
    }

    public int Sum(int idx)
    {
        int res = 0;

        while (idx > 0) {
            res += bit[idx];
            idx -= idx & -idx;
        }

        return res;
    }

    public int Query(int l, int r)
    {
        if (l > r)
            return 0;

        return Sum(r) - Sum(l - 1);
    }
}

class GFG {
    static List<int> processQueries(int[] arr,
                                    int[][] queries)
    {
        int n = arr.Length;

        BIT inc = new BIT(n);
        BIT dec = new BIT(n);

        // Build Fenwick Trees for increasing and decreasing
        // violations.
        for (int i = 1; i < n; i++) {
            if (arr[i - 1] > arr[i])
                inc.Add(i, 1);

            if (arr[i - 1] < arr[i])
                dec.Add(i, 1);
        }

        List<int> ans = new List<int>();

        for (int i = 0; i < queries.Length; i++) {
            int[] q = queries[i];
            if (q[0] == 1) {
                int idx = q[1] - 1;
                int val = q[2];

                // Remove the contribution of adjacent pairs
                // before updating.
                if (idx > 0) {
                    inc.Add(
                        idx,
                        -(arr[idx - 1] > arr[idx] ? 1 : 0));

                    dec.Add(
                        idx,
                        -(arr[idx - 1] < arr[idx] ? 1 : 0));
                }

                if (idx + 1 < n) {
                    inc.Add(
                        idx + 1,
                        -(arr[idx] > arr[idx + 1]? 1 : 0));

                    dec.Add(
                        idx + 1,
                        -(arr[idx] < arr[idx + 1]? 1 : 0));
                }

                arr[idx] = val;

                // Add the updated contribution of adjacent
                // pairs.
                if (idx > 0) {
                    inc.Add(idx, arr[idx - 1] > arr[idx]
                                     ? 1
                                     : 0);

                    dec.Add(idx, arr[idx - 1] < arr[idx]
                                     ? 1
                                     : 0);
                }

                if (idx + 1 < n) {
                    inc.Add(idx + 1, arr[idx] > arr[idx + 1]
                                         ? 1
                                         : 0);

                    dec.Add(idx + 1, arr[idx] < arr[idx + 1]
                                         ? 1
                                         : 0);
                }
            }
            else {
                int l = q[1];
                int r = q[2];

                // Count violations in the queried range.
                int badInc = inc.Query(l, r - 1);
                int badDec = dec.Query(l, r - 1);

                // Determine the order of the subarray.
                if (badInc == 0 && badDec == 0)
                    ans.Add(-1);
                else if (badInc == 0)
                    ans.Add(0);
                else if (badDec == 0)
                    ans.Add(1);
                else
                    ans.Add(-1);
            }
        }

        return ans;
    }

    static void Main()
    {
        int[] nums = { 1, 5, 7, 4, 3, 5, 9 };

        int[][] Queries = new int[][] {
            new int[] { 2, 1, 3 },
            new int[] { 1, 7, 4 },
            new int[] { 2, 6, 7 }
        };

        List<int> ans = processQueries(nums, Queries);

        // Print the result of all type-2 queries.
        Console.Write("[");

        for (int i = 0; i < ans.Count; i++) {
            if (i > 0)
                Console.Write(", ");

            Console.Write(ans[i]);
        }

        Console.Write("]");
    }
}
JavaScript
class BIT {
    constructor(sz)
    {
        this.n = sz;
        this.bit = new Array(sz + 2).fill(0);
    }

    add(idx, val)
    {
        while (idx <= this.n) {
            this.bit[idx] += val;
            idx += idx & -idx;
        }
    }

    sum(idx)
    {
        let res = 0;

        while (idx > 0) {
            res += this.bit[idx];
            idx -= idx & -idx;
        }

        return res;
    }

    query(l, r)
    {
        if (l > r)
            return 0;

        return this.sum(r) - this.sum(l - 1);
    }
}

function processQueries(arr, queries)
{
    const n = arr.length;

    const inc = new BIT(n);
    const dec = new BIT(n);

    // Build Fenwick Trees for increasing and decreasing
    // violations.
    for (let i = 1; i < n; i++) {
        if (arr[i - 1] > arr[i])
            inc.add(i, 1);

        if (arr[i - 1] < arr[i])
            dec.add(i, 1);
    }

    const ans = [];

    for (const q of queries) {

        if (q[0] === 1) {

            const idx = q[1] - 1;
            const val = q[2];

            // Remove the contribution of adjacent pairs
            // before updating.
            if (idx > 0) {
                inc.add(idx,
                        arr[idx - 1] > arr[idx] ? -1 : 0);

                dec.add(idx,
                        arr[idx - 1] < arr[idx] ? -1 : 0);
            }

            if (idx + 1 < n) {
                inc.add(idx + 1,
                        arr[idx] > arr[idx + 1] ? -1 : 0);

                dec.add(idx + 1,
                        arr[idx] < arr[idx + 1] ? -1 : 0);
            }

            arr[idx] = val;

            // Add the updated contribution of adjacent
            // pairs.
            if (idx > 0) {
                inc.add(idx,
                        arr[idx - 1] > arr[idx] ? 1 : 0);

                dec.add(idx,
                        arr[idx - 1] < arr[idx] ? 1 : 0);
            }

            if (idx + 1 < n) {
                inc.add(idx + 1,
                        arr[idx] > arr[idx + 1] ? 1 : 0);

                dec.add(idx + 1,
                        arr[idx] < arr[idx + 1] ? 1 : 0);
            }
        }
        else {

            const l = q[1];
            const r = q[2];

            // Count violations in the queried range.
            const badInc = inc.query(l, r - 1);
            const badDec = dec.query(l, r - 1);

            // Determine the order of the subarray.
            if (badInc === 0 && badDec === 0)
                ans.push(-1);
            else if (badInc === 0)
                ans.push(0);
            else if (badDec === 0)
                ans.push(1);
            else
                ans.push(-1);
        }
    }

    return ans;
}

// Driver Code
const nums = [ 1, 5, 7, 4, 3, 5, 9 ];
const Queries = [ [ 2, 1, 3 ], [ 1, 7, 4 ], [ 2, 6, 7 ] ];
const ans = processQueries(nums, Queries);
console.log("[" + ans.join(", ") + "]");

Output
[0, 1]
Comment