Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
You are given an integer array nums and an integer target.
Return the number of subarrays of nums in which target is the majority element.
The majority element of a subarray is the element that appears strictly more than half of the times in that subarray.
Example 1:
Input: nums = [1,2,2,3], target = 2
Output: 5
Explanation:
Valid subarrays with target = 2 as the majority element:
nums[1..1] = [2]nums[2..2] = [2]nums[1..2] = [2,2]nums[0..2] = [1,2,2]nums[1..3] = [2,2,3]So there are 5 such subarrays.
Example 2:
Input: nums = [1,1,1,1], target = 1
Output: 10
Explanation:
All 10 subarrays have 1 as the majority element.
Example 3:
Input: nums = [1,2,3], target = 4
Output: 0
Explanation:
target = 4 does not appear in nums at all. Therefore, there cannot be any subarray where 4 is the majority element. Hence the answer is 0.
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 1091 <= target <= 109Problem summary: You are given an integer array nums and an integer target. Return the number of subarrays of nums in which target is the majority element. The majority element of a subarray is the element that appears strictly more than half of the times in that subarray.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Segment Tree
[1,2,2,3] 2
[1,1,1,1] 1
[1,2,3] 4
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3739: Count Subarrays With Majority Element II
class BinaryIndexedTree {
private int n;
private int[] c;
public BinaryIndexedTree(int n) {
this.n = n;
this.c = new int[n + 1];
}
public void update(int x, int delta) {
for (; x <= n; x += x & -x) {
c[x] += delta;
}
}
public int query(int x) {
int s = 0;
for (; x > 0; x -= x & -x) {
s += c[x];
}
return s;
}
}
class Solution {
public long countMajoritySubarrays(int[] nums, int target) {
int n = nums.length;
BinaryIndexedTree tree = new BinaryIndexedTree(2 * n + 1);
int s = n + 1;
tree.update(s, 1);
long ans = 0;
for (int x : nums) {
s += x == target ? 1 : -1;
ans += tree.query(s - 1);
tree.update(s, 1);
}
return ans;
}
}
// Accepted solution for LeetCode #3739: Count Subarrays With Majority Element II
type BinaryIndexedTree struct {
n int
c []int
}
func NewBinaryIndexedTree(n int) *BinaryIndexedTree {
return &BinaryIndexedTree{
n: n,
c: make([]int, n+1),
}
}
func (t *BinaryIndexedTree) update(x, delta int) {
for x <= t.n {
t.c[x] += delta
x += x & -x
}
}
func (t *BinaryIndexedTree) query(x int) int {
s := 0
for x > 0 {
s += t.c[x]
x -= x & -x
}
return s
}
func countMajoritySubarrays(nums []int, target int) int64 {
n := len(nums)
tree := NewBinaryIndexedTree(2*n + 1)
s := n + 1
tree.update(s, 1)
var ans int64
for _, x := range nums {
if x == target {
s++
} else {
s--
}
ans += int64(tree.query(s - 1))
tree.update(s, 1)
}
return ans
}
# Accepted solution for LeetCode #3739: Count Subarrays With Majority Element II
class BinaryIndexedTree:
__slots__ = "n", "c"
def __init__(self, n: int):
self.n = n
self.c = [0] * (n + 1)
def update(self, x: int, delta: int) -> None:
while x <= self.n:
self.c[x] += delta
x += x & -x
def query(self, x: int) -> int:
s = 0
while x:
s += self.c[x]
x -= x & -x
return s
class Solution:
def countMajoritySubarrays(self, nums: List[int], target: int) -> int:
n = len(nums)
tree = BinaryIndexedTree(n * 2 + 1)
s = n + 1
tree.update(s, 1)
ans = 0
for x in nums:
s += 1 if x == target else -1
ans += tree.query(s - 1)
tree.update(s, 1)
return ans
// Accepted solution for LeetCode #3739: Count Subarrays With Majority Element II
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3739: Count Subarrays With Majority Element II
// class BinaryIndexedTree {
// private int n;
// private int[] c;
//
// public BinaryIndexedTree(int n) {
// this.n = n;
// this.c = new int[n + 1];
// }
//
// public void update(int x, int delta) {
// for (; x <= n; x += x & -x) {
// c[x] += delta;
// }
// }
//
// public int query(int x) {
// int s = 0;
// for (; x > 0; x -= x & -x) {
// s += c[x];
// }
// return s;
// }
// }
//
// class Solution {
// public long countMajoritySubarrays(int[] nums, int target) {
// int n = nums.length;
// BinaryIndexedTree tree = new BinaryIndexedTree(2 * n + 1);
// int s = n + 1;
// tree.update(s, 1);
// long ans = 0;
// for (int x : nums) {
// s += x == target ? 1 : -1;
// ans += tree.query(s - 1);
// tree.update(s, 1);
// }
// return ans;
// }
// }
// Accepted solution for LeetCode #3739: Count Subarrays With Majority Element II
class BinaryIndexedTree {
private n: number;
private c: number[];
constructor(n: number) {
this.n = n;
this.c = Array(n + 1).fill(0);
}
update(x: number, delta: number): void {
for (; x <= this.n; x += x & -x) {
this.c[x] += delta;
}
}
query(x: number): number {
let s = 0;
for (; x > 0; x -= x & -x) {
s += this.c[x];
}
return s;
}
}
function countMajoritySubarrays(nums: number[], target: number): number {
const n = nums.length;
const tree = new BinaryIndexedTree(2 * n + 1);
let s = n + 1;
tree.update(s, 1);
let ans = 0;
for (const x of nums) {
s += x === target ? 1 : -1;
ans += tree.query(s - 1);
tree.update(s, 1);
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
For each of q queries, scan the entire range to compute the aggregate (sum, min, max). Each range scan takes up to O(n) for a full-array query. With q queries: O(n × q) total. Point updates are O(1) but queries dominate.
Building the tree is O(n). Each query or update traverses O(log n) nodes (tree height). For q queries: O(n + q log n) total. Space is O(4n) ≈ O(n) for the tree array. Lazy propagation adds O(1) per node for deferred updates.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.