#3152
Special Array II
MediumArrayBinary SearchPrefix SumArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + m) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n + m)Space O(n)
Instead of checking each subarray for every query, we can preprocess the array to identify segments of special subarrays. This allows us to quickly determine if two indices belong to the same special segment.
⚙️
Algorithm
3 steps- 1Step 1: Create an array to store the segment identifier for each index in nums.
- 2Step 2: Traverse nums and assign a segment number to each index based on whether it continues the special property from the previous index.
- 3Step 3: For each query, check if the segment identifiers of the two indices are the same.
solution.py20 lines
1def is_special_array(nums, queries):
2 n = len(nums)
3 segments = [0] * n
4 segment_id = 0
5 segments[0] = segment_id
6
7 for i in range(1, n):
8 if (nums[i] % 2) != (nums[i - 1] % 2):
9 segment_id += 1
10 segments[i] = segment_id
11
12 results = []
13 for from_i, to_i in queries:
14 results.append(segments[from_i] == segments[to_i])
15 return results
16
17# Example usage
18nums = [4, 3, 1, 6]
19queries = [[0, 2], [2, 3]]
20print(is_special_array(nums, queries)) # Output: [False, True]ℹ
Complexity note: The time complexity is O(n + m) where n is the length of nums and m is the number of queries. We preprocess the array in O(n) and then answer each query in O(1).
- 1Identifying segments of special subarrays allows for efficient querying.
- 2Using parity checks can quickly determine if adjacent elements differ.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.