Longest Subarray Divisible by K with At Most One Negation I
Enumerate Subarrays + Modular Set
Asked at 1 company
1 recent
- Amazon
Community-reported · source · updated 2026-11-18. ● asked in the last 6 months.
Go step by step: try it yourself before the video and the visual. Progress saves on this device.
0 / 130 pointsSolved (Medium) 0/40Reviews 0/50Mastered 0/25Practice steps 0/15
Step 1
Know these before you start
Practise each one here, or tick what you already know
Watch the concept video if the pattern is new to you.
Step 2
Try it on paper
5–10 minutes, no code yet
ProblemProblem statementYou are given an integer array nums and an integer k.ReadHide
Problem Statement
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 (replacing x with -x).
Return the length of the longest valid subarray. If no valid subarray exists, return 0.
Input / Output
Input: nums = [4,1,2], k = 3
Output: 3
Explanation: Sum 7; negate 2 → 4 + 1 - 2 = 3, divisible by 3.
Input: nums = [5,3,4], k = 7
Output: 2
Explanation: [3,4] sums to 7.
Input: nums = [2,2,5], k = 6
Output: 2
Explanation: [2,2] → negate one → 0, divisible by 6.
Constraints
1 ≤ nums.length ≤ 1000
-10^5 ≤ nums[i] ≤ 10^5
1 ≤ k ≤ 10^5
Understanding the Problem
Negating x changes the sum from S to S - 2x. So a subarray is valid when:
S ≡ 0 (mod k) — no negation
S - 2x ≡ 0 (mod k) ⇔ 2x ≡ S (mod k) — for some x in the subarray
So for each subarray we need: is S mod k either 0 or in the set { 2x mod k : x in subarray }?
Edge Cases
- Negative numbers → normalise with
((v % k) + k) % k k = 1→ everything divisible → answern- No valid subarray →
0
Code it here
Tab / Shift+Tab indent · ⌘/Ctrl+/ comments · ⌘/Ctrl+Enter runs · Esc leaves the editor
Step 6
Get it accepted
All test cases pass
Step 7
Review it so it sticks
Re-solve from memory after
The step that matters most: without reviews most of a solved problem fades within weeks. Three short re-solves, each just as you start to forget, are what make it yours.
Your notes
Three lines in your own words. They come back with this problem's reviews, so you can check yourself after recalling the solution.
Solve it yourself before you look
Reading the solution first feels like progress, but it makes the next similar problem — and the interview version — much harder, because you skipped the part where you figure it out. Give it an honest 20–30 minutes. Stuck? Re-read the pattern, watch the concept video, or try the brute force first.
Hidden: approach · solution code · optimal solution
Approach
Pattern Recognition
Enumerate + Incremental State — n ≤ 1000 allows O(n²).
Fix the left end, extend right one step at a time, and update the running sum and the set of 2x mod k in O(1) per step.
Approach
Brute Force — O(n³)
For every (l, r):
S = sum(nums[l..r])
valid if S % k == 0 or any (S - 2*nums[i]) % k == 0 for i in l..r
Optimized — O(n²) time | O(k) space
seen = boolean array of size k (reused across left ends)
for l in 0..n-1:
S = 0
for r in l..n-1:
S += nums[r]
seen[(2*nums[r]) mod k] = true
if S mod k == 0 or seen[S mod k]:
best = max(best, r - l + 1)
clear only the entries set for this l (keeps it O(n²), not O(n·k))
Complexity
| Approach | Time | Space | Notes |
|---|---|---|---|
| Brute Force | O(n³) | O(1) | Recheck every element per subarray |
| Incremental Set | O(n²) | O(k) | Running sum + set of 2x mod k |
Online Compiler
Solution code
import sys
input = sys.stdin.readline
# ─────────────────────────────────────────────────────────────────────────
# OPTIMIZED — O(n²) time | O(k) space
# Negating x turns S into S - 2x → valid iff S ≡ 0 or S ≡ 2x (mod k).
# Keep the set of (2x mod k) for the current window as we extend right.
# Note: Python's % already returns a non-negative result for positive k
# ─────────────────────────────────────────────────────────────────────────
def longest_subarray(nums, k):
n, best = len(nums), 0
for l in range(n):
total = 0
seen = set() # remainders of 2x in window
for r in range(l, n):
total += nums[r] # extend window
seen.add((2 * nums[r]) % k)
target = total % k
if target == 0 or target in seen:
best = max(best, r - l + 1)
return best
# ── Input ─────────────────────────────────────────────────────────────────
n, k = map(int, input().split())
nums = list(map(int, input().split()))
print(longest_subarray(nums, k))Other ways to solve it
- Thought of another approach (slower, or cleverer)? Code it here: the same tests check any approach.
- Community solutions on LeetCode ↗ for many more versions, in many languages. Read them after you've solved it.
Revising this one?
- →Solve it from memory before peeking
- →Say the pattern out loud, not just the code
- →Explain it like you would to a friend
- →Try it again in a different language