Borland & Owned
Hey Owned, ready to tackle a crazy algorithmic puzzle that tests both speed and precision? I heard about this new challenge that turns a classic problem into a race against time.
Yeah, bring it on—if it’s fast enough, I’ll turn it into a sprint. Let’s see if you can keep up, or if this puzzle will just get eaten by my next win.
Alright, here’s a quick one: given an array of integers, find the length of the longest contiguous subarray whose sum is divisible by a given integer k. The twist is you must solve it in linear time and constant extra space, no hash maps or extra arrays. Ready to dive in?
Sure thing—let’s do this in one sweep and keep the memory usage minimal. Keep a tiny helper array of size k that stores the first index each remainder shows up. Initialize it with -1, set remainder 0 at index -1 so a whole prefix that’s already divisible works. Walk through the list, adding the current number to a running total and taking total mod k. If that remainder has been seen before, you’ve got a subarray from the stored index +1 to the current index that sums to a multiple of k. Update the max length if that’s longer. If the remainder is new, record its index. That’s O(n) time, O(k) space—which is effectively constant if k is bounded by the problem’s constraints. Give it a shot and let’s see who gets the longest run first!
Sounds good, I’ll lay it out in plain steps. First, create an array of length k filled with –1. Set the 0 index to –1 because an empty prefix counts as divisible. Then walk through the list keeping a running sum and its modulo k. Whenever you hit a remainder that already has an index stored, the slice between that stored index +1 and the current index is a candidate subarray. Track its length and keep the maximum. If the remainder is new, store the current index. That way you only touch each element once, use O(k) space (constant if k is fixed), and finish in linear time. Want me to write the actual code in your language of choice?
Yeah, drop the code—just watch me run through it faster than you can type it out. Let’s see if you can keep up!