Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 128 additions & 0 deletions .claude/skills/add-solution/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
---
name: add-solution
description: Add a LeetCode solution write-up to this repo following its conventions. Use when the user wants to add/create a solution for a LeetCode problem (given a URL, problem id/title, and/or code in one or more languages). Creates the difficulty/<id>.<Title> folder, writes solution.md (+ optional description.md), and updates the README index.
---

# Add LeetCode Solution

Automates adding a new solution to this repository. Follow these steps in order.

## 1. Resolve the problem metadata

You need: **problem id**, **exact title**, **difficulty** (Easy/Medium/Hard), and the
**statement/examples/constraints**.

- If given a LeetCode URL, extract the `titleSlug` (the path segment after
`/problems/`).
- `WebFetch` on leetcode.com usually returns **403** — do not rely on it. Instead
query the GraphQL API for everything in one call:

```bash
curl -s 'https://leetcode.com/graphql' \
-H 'Content-Type: application/json' -H 'User-Agent: Mozilla/5.0' \
--data '{"query":"query q($titleSlug:String!){question(titleSlug:$titleSlug){questionFrontendId title difficulty content}}","variables":{"titleSlug":"<TITLE-SLUG>"}}'
```

`questionFrontendId` is the problem id, `difficulty` maps to the folder, and
`content` is the HTML statement (convert to clean markdown for `description.md`).
- If the user already supplied id/title/difficulty, trust those; only fetch what's
missing.

## 2. Create the folder

```text
<Difficulty>/<id>.<Problem-Title-With-Hyphens>/
```

- Difficulty is `Easy`, `Medium`, or `Hard` (matches LeetCode).
- Title: replace spaces with hyphens, keep the original casing and roman numerals
(e.g. `3739.Count-Subarrays-With-Majority-Element-II`).
- Use `mkdir -p`.

## 3. Write `solution.md`

Use the repo template exactly:

```md
# Intuition

Brief explanation of the key insight.

# Approach: <Technique Name>

Step-by-step algorithm description.

# Complexity

- Time complexity: ...
- Space complexity: ...

# Code

## Go

```go
...
```

## Rust

```rust
...
```
```

Rules:

- One `solution.md` with `## Go`, `## Rust`, `## C++` sub-sections under `# Code`
when documenting multiple languages. Use a single language-specific file
(`solution-go.md`, `solution-rust.md`, `solution-cpp.md`) only when the user
asks for that layout or just one language with extra context.
- Use `$...$` for inline math in the complexity section when helpful.
- Keep explanations concise and focused on **why** the approach works.
- Paste the user's code verbatim (only fix obvious formatting); do not invent a
different algorithm than what they provided.
- No empty placeholder sections.

## 4. Write `description.md` (optional but preferred)

Convert the GraphQL `content` HTML into markdown: a title heading, the statement,
`## Example N` blocks (in fenced ```text), and a `## Constraints` list. Use `^` for
exponents (e.g. `10^5`).

## 5. Update `README.md`

`README.md` has per-difficulty tables and counts.

1. Add a row to the matching difficulty table, kept in ascending id order:

```md
| <id>. <Title> | [Link](https://leetcode.com/problems/<slug>/) | [main](<Difficulty>/<folder>/solution.md) |
```

- The solution column links each variant: `main` for `solution.md`, or the
suffix label for `solution-<variant>.md`, joined with ` · `
(e.g. `[go](...) · [rust](...) · [main](...)`).

2. Increment the difficulty header count, e.g. `### Hard (27)` → `### Hard (28)`.
3. Increment the total near the top:
`Total: **N** problems with at least one solution file.`

Also update the count in `CLAUDE.md` ("The index currently lists **N** problems.")
if you bump the README total.

## 6. Git (only if the user asks)

Do not commit or open a PR unless asked. When asked:

- Create a feature branch (e.g. `add-<id>-<short-slug>`).
- Commit message: `Add solution for <id>. <Problem Title>`
- Open a PR against `main`; do not push unless asked.

## Verification checklist

- [ ] Folder under the correct difficulty, named `<id>.<Title-With-Hyphens>`.
- [ ] `solution.md` follows the template; code compiles logically and matches the
stated complexity.
- [ ] README row added in id order with working relative links.
- [ ] README difficulty count and total incremented; CLAUDE.md count synced.
47 changes: 47 additions & 0 deletions Hard/3739.Count-Subarrays-With-Majority-Element-II/description.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# 3739. Count Subarrays With Majority Element II

Hard

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

```text
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

```text
Input: nums = [1,1,1,1], target = 1
Output: 10
Explanation: All 10 subarrays have 1 as the majority element.
```

## Example 3

```text
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 <= 10^5`
- `1 <= nums[i] <= 10^9`
- `1 <= target <= 10^9`
94 changes: 94 additions & 0 deletions Hard/3739.Count-Subarrays-With-Majority-Element-II/solution.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# Intuition

`target` is the majority of a subarray iff it appears strictly more than half the
time. Replace every `target` with `+1` and every other value with `-1`. Then a
subarray has `target` as its majority element exactly when the sum of its `±1`
values is **strictly positive** (more `+1`s than `-1`s).

Using prefix sums $P_0, P_1, \dots, P_n$ (with $P_0 = 0$), the subarray
`(i, j]` is valid iff $P_j - P_i > 0$, i.e. $P_i < P_j$. So the answer is the
number of index pairs $i < j$ with $P_i < P_j$.

# Approach: Prefix Sum + Running Count of Smaller Prefixes

We sweep `j` from left to right and, for each `j`, add the number of earlier
prefixes (including the empty prefix $P_0$) that are strictly smaller than the
current prefix $P_j$.

Naively counting "how many earlier prefixes are smaller" looks like it needs a
Fenwick tree, but the prefix sum changes by exactly `±1` at each step, so we can
maintain that count incrementally in $O(1)$:

- Shift prefix values by `n` so they fit into an array of size `2n + 1`.
`count` tracks the current prefix sum (shifted), starting at `n` (value `0`).
- `prefix[v]` = how many prefixes seen so far equal the value `v`.
Seed `prefix[n] = 1` for the empty prefix $P_0 = 0$.
- `sum` = how many earlier prefixes are strictly smaller than the current one.

Transitions when the prefix value moves:

- `num == target` → value goes up by 1. Everything that equalled the old value
is now strictly smaller, so `sum += prefix[count]`, then `count++`.
- `num != target` → value goes down by 1. After `count--`, everything that
equals this new value is no longer strictly smaller, so `sum -= prefix[count]`.

After updating, record the current prefix with `prefix[count]++` and accumulate
`ans += sum`. Because `sum` already counts how many strictly-smaller prefixes
precede `j`, this directly sums the valid `(i, j]` subarrays ending at each `j`.

# Complexity

- Time complexity: $O(n)$ — one pass with $O(1)$ work per element.
- Space complexity: $O(n)$ — the `prefix` frequency array of size $2n + 1$.

# Code

## Go

```go
func countMajoritySubarrays(nums []int, target int) int64 {
n := len(nums)
prefix := make([]int, 2*n+1)
prefix[n] = 1
count := n
ans, sum := 0, 0
for _, num := range nums {
if num == target {
sum += prefix[count]
count++
} else {
count--
sum -= prefix[count]
}
prefix[count]++
ans += sum
}
return int64(ans)
}
Comment on lines +49 to +67
```

## Rust

```rust
impl Solution {
pub fn count_majority_subarrays(nums: Vec<i32>, target: i32) -> i64 {
let n = nums.len();
let mut prefix = vec![0; 2 * n + 1];
prefix[n] = 1;
let mut count = n;
let (mut ans, mut sum) = (0_i64, 0_i64);
for num in nums.into_iter() {
if num == target {
sum += prefix[count] as i64;
count += 1;
} else {
count -= 1;
sum -= prefix[count] as i64;
}
prefix[count] += 1;
ans += sum;
}
ans
}
}
```
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Easy/350.Intersection-of-Two-Arrays-II/

## Solutions index

Total: **159** problems with at least one solution file.
Total: **160** problems with at least one solution file.

Solution links use variant names when multiple approaches or languages exist (`main` = `solution.md`, others = `solution-<variant>.md`).

Expand Down Expand Up @@ -165,7 +165,7 @@ Solution links use variant names when multiple approaches or languages exist (`m
| 3218. Minimum Cost for Cutting Cake I | [Link](https://leetcode.com/problems/minimum-cost-for-cutting-cake-i/) | [main](Medium/3218.Minimum-Cost-for-Cutting-Cake-I/solution.md) |
| 3254. Find the Power of K Size Subarrays I | [Link](https://leetcode.com/problems/find-the-power-of-k-size-subarrays-i/) | [main](Medium/3254.Find-the-Power-of-K-Size-Subarrays-I/solution.md) |

### Hard (27)
### Hard (28)

| Problem | LeetCode | Solution |
|---------|----------|----------|
Expand Down Expand Up @@ -196,3 +196,4 @@ Solution links use variant names when multiple approaches or languages exist (`m
| 2751. Robot Collisions | [Link](https://leetcode.com/problems/robot-collisions/) | [main](Hard/2751.Robot-Collisions/solution.md) |
| 3219. Minimum Cost for Cutting Cake II | [Link](https://leetcode.com/problems/minimum-cost-for-cutting-cake-ii/) | [main](Hard/3219.Minimum-Cost-for-Cutting-Cake-II/solution.md) |
| 3363. Find the Maximum Number of Fruits Collected | [Link](https://leetcode.com/problems/find-the-maximum-number-of-fruits-collected/) | [main](Hard/3363. Find-the-Maximum-Number-of-Fruits-Collected/solution.md) |
| 3739. Count Subarrays With Majority Element II | [Link](https://leetcode.com/problems/count-subarrays-with-majority-element-ii/) | [main](Hard/3739.Count-Subarrays-With-Majority-Element-II/solution.md) |