DEV Community

Nithya Dharshini official
Nithya Dharshini official

Posted on

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:

  1. Build the first window sum.
  2. Slide the window.
  3. Remove the leaving element.
  4. Add the entering element.
  5. Because the array is circular, we use:
  6. index % n
  7. to wrap around the array.

C++ Implementation

class Solution {
public:
    vector<int> decrypt(vector<int>& code, int k) {
        vector<int> v(code.size(),0);
        int n = code.size();

        if(k == 0) return v;

        int start = (k > 0) ? 1 : n + k;
        int end   = (k > 0) ? k : n - 1;

        int winSum = 0;

        for(int i = start; i <= end; ++i){
            winSum += code[i];
        }

        for(int i = 0; i < n; ++i){
            v[i] = winSum;

            winSum -= code[start % n];
            winSum += code[(end + 1) % n];

            start++;
            end++;
        }

        return v;
    }
};

Enter fullscreen mode Exit fullscreen mode

Complexity

Time Complexity - O(n)
We traverse the array only once.

Space Complexity - O(n)
For storing the result.

What I Learned

  • Sliding Window can work on circular arrays
  • % n helps wrap indexes
  • Instead of recalculating sums, we update the window efficiently

Small problem, but a great practice for advanced sliding window thinking.

Top comments (0)