Taro Logo

Peaks in Array

#2 Most AskedHard
12 views
Topics:
Arrays

A peak in an array arr is an element that is greater than its previous and next element in arr.

You are given an integer array nums and a 2D integer array queries.

You have to process queries of two types:

  • queries[i] = [1, li, ri], determine the count of peak elements in the subarray nums[li..ri].
  • queries[i] = [2, indexi, vali], change nums[indexi] to vali.

Return an array answer containing the results of the queries of the first type in order.

Notes:

  • The first and the last element of an array or a subarray cannot be a peak.

Example 1:

Input: nums = [3,1,4,2,5], queries = [[2,3,4],[1,0,4]]

Output: [0]

Explanation:

First query: We change nums[3] to 4 and nums becomes [3,1,4,4,5].

Second query: The number of peaks in the [3,1,4,4,5] is 0.

Example 2:

Input: nums = [4,1,4,2,1,5], queries = [[2,2,4],[1,0,2],[1,0,4]]

Output: [0,1]

Explanation:

First query: nums[2] should become 4, but it is already set to 4.

Second query: The number of peaks in the [4,1,4] is 0.

Third query: The second 4 is a peak in the [4,1,4,2,1].

Constraints:

  • 3 <= nums.length <= 105
  • 1 <= nums[i] <= 105
  • 1 <= queries.length <= 105
  • queries[i][0] == 1 or queries[i][0] == 2
  • For all i that:
    • queries[i][0] == 1: 0 <= queries[i][1] <= queries[i][2] <= nums.length - 1
    • queries[i][0] == 2: 0 <= queries[i][1] <= nums.length - 1, 1 <= queries[i][2] <= 105

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the first or last index of a queried subarray ever count as a peak?
  2. Must a peak be strictly greater than both neighboring values?
  3. Does an update replace one index and become visible to every later count?
  4. Are the two ends of a count query inclusive bounds that themselves cannot be peaks?
  5. Is the peak count zero when the queried subarray has fewer than three positions?

Brute Force Solution

Approach

One requested span is scanned directly. The walk starts just after the left bound and stops just before the right bound, because those two positions cannot be peaks. Each interior value is counted when it is strictly greater than the neighbor on each side.

Here's how the algorithm would work step-by-step:

  1. Start the count at zero.
  2. Visit every index strictly between the left bound and the right bound.
  3. Read the value at that index together with its two neighbors.
  4. Accept the index when it is strictly greater than both neighbors.
  5. Add one for each accepted index.
  6. Return the count for that single span.

Code Implementation

def count_peaks_in_subarray_brute_force(numbers, start_index, end_index):
    peak_count = 0
    
    # Iterate through the subarray, excluding the first and last elements since they cannot be peaks.
    for current_index in range(start_index + 1, end_index):
        number_to_check = numbers[current_index]
        left_neighbor = numbers[current_index - 1]
        right_neighbor = numbers[current_index + 1]

        # A peak must be strictly greater than both of its immediate neighbors.
        is_peak = number_to_check > left_neighbor and number_to_check > right_neighbor
        
        # We only count the element if it meets the definition of a peak.
        if is_peak:
            peak_count += 1
            
    return peak_count

Big(O) Analysis

Time Complexity
O(n) – Let n be the length of the array. A single count walks the indexes inside the requested span. The span contains at most n positions, and each position does a constant amount of comparing. There is no preprocessing, so one count of a span no longer than the whole array takes O(n) time.
Space Complexity
O(1) – The scan keeps the running count and the index being examined. The array is read in place. No peak table is built. The call uses a constant amount of extra memory. The extra memory is O(1).

Optimal Solution

Approach

A binary indexed tree stores a one at every index that is currently a peak and a zero everywhere else. Building it marks the initial peaks, a count reads the sum of marks strictly inside the requested span, and an update recomputes the peak status of the changed index and its two neighbors. Only a mark that flips is added or removed in the tree.

Here's how the algorithm would work step-by-step:

  1. Create a tree with one slot per array index, initially all zeros.
  2. Mark every interior index that is strictly taller than both neighbors.
  3. For a count, reject a span that has no interior index.
  4. Otherwise sum the marks from just after the left bound through just before the right bound.
  5. Before an update, remember whether the changed index and its two neighbors are peaks.
  6. Write the new value, then recheck those same indexes.
  7. Add one to the tree when a peak appears and subtract one when a peak disappears.

Code Implementation

class FenwickTree:
    def __init__(self, size):
        self.tree_sums = [0] * (size + 1)

    def update(self, index, delta):
        index += 1
        while index < len(self.tree_sums):
            self.tree_sums[index] += delta
            index += index & (-index)

    def query(self, index):
        index += 1
        current_sum = 0
        while index > 0:
            current_sum += self.tree_sums[index]
            index -= index & (-index)
        return current_sum

    def query_range(self, start_index, end_index):
        if start_index > end_index:
            return 0
        end_sum = self.query(end_index)
        start_sum = self.query(start_index - 1)
        return end_sum - start_sum

class PeaksInArraySolver:
    def __init__(self, numbers):
        self.numbers = numbers
        self.number_of_elements = len(numbers)
        self.peak_markers = [0] * self.number_of_elements
        self.fenwick_tree = FenwickTree(self.number_of_elements)
        self._initialize_peaks()

    def _is_peak(self, index):
        if 1 <= index < self.number_of_elements - 1:
            return self.numbers[index] > self.numbers[index - 1] and self.numbers[index] > self.numbers[index + 1]
        return False

    def _initialize_peaks(self):
        # Pre-calculating all initial peaks ensures our data structure is ready for fast queries.
        for index in range(1, self.number_of_elements - 1):
            if self._is_peak(index):
                self.peak_markers[index] = 1
                self.fenwick_tree.update(index, 1)

    def count_peaks_in_range(self, start_index, end_index):
        # Querying the tree is much faster than re-scanning the array for every request.
        if start_index + 1 > end_index - 1:
            return 0
        return self.fenwick_tree.query_range(start_index + 1, end_index - 1)

    def update_value(self, index, new_value):
        affected_indices = {index - 1, index, index + 1}
        old_peak_states = {}
        for affected_index in affected_indices:
            if 0 <= affected_index < self.number_of_elements:
                old_peak_states[affected_index] = self._is_peak(affected_index)

        self.numbers[index] = new_value

        # Updating the Fenwick tree only for changed peak statuses avoids redundant calculations.
        for affected_index in affected_indices:
            if 0 <= affected_index < self.number_of_elements:
                new_peak_state = self._is_peak(affected_index)
                old_peak_state = old_peak_states.get(affected_index, False)

                if new_peak_state != old_peak_state:
                    # The delta is +1 for a new peak, -1 for a removed peak.
                    delta = 1 if new_peak_state else -1
                    self.peak_markers[affected_index] = 1 if new_peak_state else 0
                    self.fenwick_tree.update(affected_index, delta)

Big(O) Analysis

Time Complexity
O((n + q) log n) – Let n be the array length and let q be the number of later counts and updates. Preparing the tree visits each interior index once, and writing a mark walks a logarithmic number of tree slots. A count reads two prefixes, and each prefix is also logarithmic. An update inspects at most three indexes and writes a mark only when the peak status changes. Across preparation and every later operation, the total time is O((n + q) log n).
Space Complexity
O(n) – The tree array has one slot per index plus a leading zero, so it is proportional to n. A parallel array remembers the current mark at each index. The values themselves are kept so peak checks can read neighbors. A few indexes are reused during an update. The extra memory is O(n).

Edge Cases

The queried span has fewer than three positions
How to Handle:
There is no interior index, so the count is zero.
A value only ties one of its neighbors
How to Handle:
It is not a peak and does not add to the count.
An update creates a new peak
How to Handle:
The stored mark for that index increases by one before later counts.
An update removes a peak
How to Handle:
The stored mark decreases by one so the index is left out of later counts.
An endpoint of the whole array changes
How to Handle:
That endpoint stays ineligible as a peak, while its inner neighbor may gain or lose peak status.
A count covers the entire array
How to Handle:
Every current interior peak is included, and the two ends are left out.
0/26 completed