Longest Subarray Divisible by K with At Most One Negation II Problem
Description
LeetCode Problem 4064.
You are given an integer array nums and an integer k.
A subarray is valid if its sum is divisible by k, or can become divisible by k by negating one element within that subarray.
Negating an element means replacing its value x with -x.
Return the length of the longest valid subarray. If no valid subarray exists, return 0.
Example 1:
Input: nums = [4,1,2], k = 3
Output: 3
Explanation:
- The sum of the entire array is 7, and 7 % 3 = 1, so it is not divisible by k = 3.
- Negating nums[2] = 2 changes the sum to 4 + 1 − 2 = 3, which is divisible by k.
- Therefore, the entire array is a valid subarray, giving a length of 3.
Example 2:
Input: nums = [5,3,4], k = 7
Output: 2
Explanation:
- The sum of the entire array is 12, and negating any one of its elements does not make its sum divisible by 7.
- However, the subarray [3, 4] has a sum of 7, which is divisible by k = 7 without any negation.
- Therefore, the longest valid subarray has a length of 2.
Example 3:
Input: nums = [2,2,5], k = 6
Output: 2
Explanation:
- The sum of the entire array is 9, and negating any one of its elements does not make its sum divisible by 6.
- The subarray [2, 2] has a sum of 4. Negating either element changes it to [-2, 2] or [2, -2], both of which have a sum of 0.
- Therefore, the longest valid subarray has a length of 2.
Constraints:
1 <= nums.length <= 10^5-10^5 <= nums[i] <= 10^51 <= k <= 3000
Solution
Approach: Prefix Remainders and First Occurrences
Let p[i] be the prefix sum modulo k. A subarray (j, i] is valid when either p[i] == p[j], or negating one element x in it fixes the sum: negating changes the sum by -2x, so we need p[i] - p[j] - 2x to be divisible by k for some x inside the subarray.
For a fixed element x = nums[t] with remainder a, any start j <= t works as long as p[j] + 2a == p[i] (mod k). Because we want the longest subarray, for each remainder q we only need its first occurrence first[q].
Sweep t from left to right and keep best[s], the smallest start index that can produce the end remainder s using an element seen so far. When we reach an element with remainder a, the new starts that become usable are the remainders q whose first occurrence is at most t. For each such q (handled once per value of a, using a pointer into the remainders sorted by first occurrence) update best[(q + 2a) % k] = min(..., first[q]). The remainders with p[i] == p[j] (no negation) are in best from the start. Then the subarray ending at i has length i + 1 - best[p[i+1]] when that start exists.
Each of the k pointers moves at most k steps in total, so the extra work is O(k^2).
The Python version uses the same facts in a form that runs on built-in list operations, because the pointer loop is slow there. A longest valid subarray can always start at some first[q] and end just before some last[t], where last[t] is the last occurrence of the prefix remainder t. The pair works when t == q, or when an element with remainder a and 2a == t - q (mod k) lies between the two. Go through the remainders q in order of first[q], keeping for every value u = 2a % k the next index at or after first[q] of an element with such a remainder. Rotating last by q lines up last[q + u] with that index, so one comparison over the whole list finds the best end for this start. Stop as soon as n - first[q] cannot beat the answer.
Complexity: O(n + k2) time (plus sorting k remainders) and O(n + k) extra space.
from itertools import compress
from operator import gt
class Solution:
def longestSubarray(self, nums: List[int], k: int) -> int:
n = len(nums)
p = [0] * (n + 1)
for i in range(n):
p[i + 1] = (p[i] + nums[i]) % k
first = [-1] * k
last = [-1] * k
for i in range(n + 1):
if first[p[i]] == -1:
first[p[i]] = i
last[p[i]] = i
# The longest valid subarray can start at first[q] and end just before last[t].
# (first[q], last[t]) works when t == q, or when some element with 2 * a == t - q (mod k)
# lies between them. With u = 2a % k, that is t = q + u, so we look at the rotation of last by q.
res = [x % k for x in nums]
inf = n + 5
nxt_a = [inf] * k # next index >= the current start with remainder a
for j in range(n - 1, -1, -1):
nxt_a[res[j]] = j
later = [inf] * n # next index after j with the same remainder
seen = [inf] * k
for j in range(n - 1, -1, -1):
later[j] = seen[res[j]]
seen[res[j]] = j
nxt_u = [inf] * k # nxt_u[u]: the earliest next index among the remainders a with 2a % k == u
for a in range(k):
u = 2 * a % k
nxt_u[u] = min(nxt_u[u], nxt_a[a])
ans = 0
start = 0
for q in sorted((q for q in range(k) if first[q] != -1), key=lambda q: first[q]):
f = first[q]
if n - f <= ans:
break
while start < f: # move the start right past index `start`
a = res[start]
nxt_a[a] = later[start]
u = 2 * a % k
b = (a + k // 2) % k if k % 2 == 0 else a
nxt_u[u] = min(nxt_a[a], nxt_a[b])
start += 1
ans = max(ans, last[q] - f)
rot = last[q:] + last[:q] # rot[u] = last[(q + u) % k]
# need an element index in [f, last[t] - 1], i.e. nxt_u[u] < rot[u]
best = max(compress(rot, map(gt, rot, nxt_u)), default=-1)
if best > f:
ans = max(ans, best - f)
return ans