
Sliding Window on a Circular Array — Defuse the Bomb (LeetCode 1652)
Today I solved an interesting Sliding Window problem on a circular array.This problem helped me understand how sliding windows work when the array wraps around. Problem Summary We are given: A circular array code and an integer k. We must replace each element with a sum of other elements depending on k. Rules : If k > 0 → sum of the next k elements If k < 0 → sum of the previous |k| elements If k = 0 → result is 0 Important : The array is circular.That means: code[n-1] → next element is code[0] code[0] → previous element is code[n-1] Example Input: -> code = [5,7,1,4] , k = 3 Result: -> [12,10,16,13] Because : 5 → 7 + 1 + 4 = 12 7 → 1 + 4 + 5 = 10 1 → 4 + 5 + 7 = 16 4 → 5 + 7 + 1 = 13 Idea Instead of recalculating sums again and again, we use a Sliding Window. Steps : Build the first window sum. Slide the window. Remove the leaving element. Add the entering element. Because the array is circular, we use: index % n to wrap around the array. C++ Implementation class Solution { public: ve
Continue reading on Dev.to Beginners
Opens in a new tab



