LeetCode #3569 — HARD

Maximize Count of Distinct Primes After Split

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

You are given an integer array nums having length n and a 2D integer array queries where queries[i] = [idx, val].

For each query:

  1. Update nums[idx] = val.
  2. Choose an integer k with 1 <= k < n to split the array into the non-empty prefix nums[0..k-1] and suffix nums[k..n-1] such that the sum of the counts of distinct prime values in each part is maximum.

Note: The changes made to the array in one query persist into the next query.

Return an array containing the result for each query, in the order they are given.

Example 1:

Input: nums = [2,1,3,1,2], queries = [[1,2],[3,3]]

Output: [3,4]

Explanation:

  • Initially nums = [2, 1, 3, 1, 2].
  • After 1st query, nums = [2, 2, 3, 1, 2]. Split nums into [2] and [2, 3, 1, 2]. [2] consists of 1 distinct prime and [2, 3, 1, 2] consists of 2 distinct primes. Hence, the answer for this query is 1 + 2 = 3.
  • After 2nd query, nums = [2, 2, 3, 3, 2]. Split nums into [2, 2, 3] and [3, 2] with an answer of 2 + 2 = 4.
  • The output is [3, 4].

Example 2:

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

Output: [0]

Explanation:

  • Initially nums = [2, 1, 4].
  • After 1st query, nums = [1, 1, 4]. There are no prime numbers in nums, hence the answer for this query is 0.
  • The output is [0].

Constraints:

  • 2 <= n == nums.length <= 5 * 104
  • 1 <= queries.length <= 5 * 104
  • 1 <= nums[i] <= 105
  • 0 <= queries[i][0] < nums.length
  • 1 <= queries[i][1] <= 105
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given an integer array nums having length n and a 2D integer array queries where queries[i] = [idx, val]. For each query: Update nums[idx] = val. Choose an integer k with 1 <= k < n to split the array into the non-empty prefix nums[0..k-1] and suffix nums[k..n-1] such that the sum of the counts of distinct prime values in each part is maximum. Note: The changes made to the array in one query persist into the next query. Return an array containing the result for each query, in the order they are given.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Math · Segment Tree

Example 1

[2,1,3,1,2]
[[1,2],[3,3]]

Example 2

[2,1,4]
[[0,1]]
Step 02

Core Insight

What unlocks the optimal approach

  • Preprocess all primes up to <code>max(nums)</code> with a sieve to enable O(1) primality checks.
  • For each prime <code>p</code>, record its occurrence <code>indices</code>; if it appears at least twice, treat <code>[first, last]</code> as a segment, and note that the split position <code>k</code> with the most overlapping segments equals the number of primes counted on both sides.
  • Use a segment tree with lazy propagation over all possible <code>k</code> to maintain, update, and query the sum of distinct-prime counts in the prefix and suffix, adjusting for overlaps.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3569: Maximize Count of Distinct Primes After Split
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3569: Maximize Count of Distinct Primes After Split
// package main
// 
// import (
// 	"github.com/emirpasic/gods/v2/trees/redblacktree"
// 	"math/bits"
// )
// 
// // https://space.bilibili.com/206214
// const mx int = 1e5
// 
// var np = [mx + 1]bool{true, true}
// 
// func init() {
// 	for i := 2; i <= mx; i++ {
// 		if !np[i] {
// 			for j := i * i; j <= mx; j += i {
// 				np[j] = true
// 			}
// 		}
// 	}
// }
// 
// type lazySeg []struct {
// 	l, r int
// 	mx   int
// 	todo int
// }
// 
// func mergeInfo(a, b int) int {
// 	return max(a, b)
// }
// 
// const todoInit = 0
// 
// func mergeTodo(f, old int) int {
// 	return f + old
// }
// 
// func (t lazySeg) apply(o int, f int) {
// 	cur := &t[o]
// 	cur.mx += f
// 	cur.todo = mergeTodo(f, cur.todo)
// }
// 
// func (t lazySeg) maintain(o int) {
// 	t[o].mx = mergeInfo(t[o<<1].mx, t[o<<1|1].mx)
// }
// 
// func (t lazySeg) spread(o int) {
// 	f := t[o].todo
// 	if f == todoInit {
// 		return
// 	}
// 	t.apply(o<<1, f)
// 	t.apply(o<<1|1, f)
// 	t[o].todo = todoInit
// }
// 
// func (t lazySeg) build(a []int, o, l, r int) {
// 	t[o].l, t[o].r = l, r
// 	t[o].todo = todoInit
// 	if l == r {
// 		t[o].mx = a[l]
// 		return
// 	}
// 	m := (l + r) >> 1
// 	t.build(a, o<<1, l, m)
// 	t.build(a, o<<1|1, m+1, r)
// 	t.maintain(o)
// }
// 
// func (t lazySeg) update(o, l, r int, f int) {
// 	if l <= t[o].l && t[o].r <= r {
// 		t.apply(o, f)
// 		return
// 	}
// 	t.spread(o)
// 	m := (t[o].l + t[o].r) >> 1
// 	if l <= m {
// 		t.update(o<<1, l, r, f)
// 	}
// 	if m < r {
// 		t.update(o<<1|1, l, r, f)
// 	}
// 	t.maintain(o)
// }
// 
// func (t lazySeg) query(o, l, r int) int {
// 	if l <= t[o].l && t[o].r <= r {
// 		return t[o].mx
// 	}
// 	t.spread(o)
// 	m := (t[o].l + t[o].r) >> 1
// 	if r <= m {
// 		return t.query(o<<1, l, r)
// 	}
// 	if l > m {
// 		return t.query(o<<1|1, l, r)
// 	}
// 	return mergeInfo(t.query(o<<1, l, r), t.query(o<<1|1, l, r))
// }
// 
// func newLazySegmentTreeWithArray(a []int) lazySeg {
// 	n := len(a)
// 	t := make(lazySeg, 2<<bits.Len(uint(n-1)))
// 	t.build(a, 1, 0, n-1)
// 	return t
// }
// 
// func newLazySegmentTree(n int, initVal int) lazySeg {
// 	a := make([]int, n)
// 	for i := range a {
// 		a[i] = initVal
// 	}
// 	return newLazySegmentTreeWithArray(a)
// }
// 
// func maximumCount(nums []int, queries [][]int) (ans []int) {
// 	n := len(nums)
// 	pos := map[int]*redblacktree.Tree[int, struct{}]{}
// 	for i, x := range nums {
// 		if np[x] {
// 			continue
// 		}
// 		if _, ok := pos[x]; !ok {
// 			pos[x] = redblacktree.New[int, struct{}]()
// 		}
// 		pos[x].Put(i, struct{}{})
// 	}
// 
// 	t := newLazySegmentTree(n, 0)
// 	for _, ps := range pos {
// 		if ps.Size() > 1 {
// 			t.update(1, ps.Left().Key, ps.Right().Key, 1)
// 		}
// 	}
// 
// 	update := func(ps *redblacktree.Tree[int, struct{}], i, delta int) {
// 		l, r := ps.Left().Key, ps.Right().Key
// 		if l == r {
// 			t.update(1, min(l, i), max(r, i), delta)
// 		} else if i < l {
// 			t.update(1, i, l-1, delta)
// 		} else if i > r {
// 			t.update(1, r+1, i, delta)
// 		}
// 	}
// 
// 	for _, q := range queries {
// 		i, v := q[0], q[1]
// 		old := nums[i]
// 		nums[i] = v
// 
// 		if !np[old] {
// 			ps := pos[old]
// 			ps.Remove(i)
// 			if ps.Empty() {
// 				delete(pos, old)
// 			} else {
// 				update(ps, i, -1)
// 			}
// 		}
// 
// 		if !np[v] {
// 			if ps, ok := pos[v]; !ok {
// 				pos[v] = redblacktree.New[int, struct{}]()
// 			} else {
// 				update(ps, i, 1)
// 			}
// 			pos[v].Put(i, struct{}{})
// 		}
// 
// 		ans = append(ans, len(pos)+t.query(1, 0, n-1))
// 	}
// 	return
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n + q log n)
Space
O(n)

Approach Breakdown

BRUTE FORCE
O(n × q) time
O(1) space

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.

SEGMENT TREE
O(n + q log n) time
O(n) space

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.

Shortcut: Build O(n), query/update O(log n) each. When you need both range queries AND point updates.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

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.

Overflow in intermediate arithmetic

Wrong move: Temporary multiplications exceed integer bounds.

Usually fails on: Large inputs wrap around unexpectedly.

Fix: Use wider types, modular arithmetic, or rearranged operations.