Python 1652.py
class Solution:
def decrypt(self, code: List[int], k: int) -> List[int]:
size = len(code)
delta = +1 if k > 0 else -1
for i in range(size):
have = 0
# if k == 0 then no iterations
for j in range(1, abs(k) + 1):
pos = (i + j * delta) % size
have += code[pos]
yield have
Difficulty
and has an acceptance rate of about 79% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Sliding Window
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a single method decrypt. The method receives an integer list code and an integer k, then produces a sequence where each element is the sum of a contiguous block of k numbers taken from code. Positive k values cause the sum to be taken from the next k positions, negative k values from the previous k positions, and a zero k results in a sum of zero for every position. The method uses a generator (yield) to emit each computed sum, allowing the caller to iterate lazily over the results.
Key Steps
Determining the traversal direction
size = len(code)
delta = +1 if k > 0 else -1
The length of the input list is stored in size for repeated use, avoiding repeated calls to len. The variable delta encodes the direction of traversal: a positive step when k is positive, and a negative step when k is negative. This single assignment eliminates the need for conditional logic inside the inner loop.
Iterating over each index of the input list
for i in range(size):
have = 0
The outer loop walks through every index i of code. A local accumulator have is reset for each position, ensuring that the sum for the current index starts from zero.
Summing the required elements
for j in range(1, abs(k) + 1):
pos = (i + j * delta) % size
have += code[pos]
The inner loop runs exactly abs(k) times, which naturally handles the case k == 0 by performing zero iterations, leaving have as zero. The expression pos = (i + j * delta) % size computes the target index while automatically wrapping around the list boundaries using the modulo operator. By multiplying j with delta, the same arithmetic works for both forward and backward traversals, removing duplicate code paths.
Emitting the result
yield have
Instead of building a new list, the method yields each computed sum as soon as it is ready. This lazy generation reduces peak memory consumption, especially for large input lists, because only one accumulator value needs to reside in memory at any time.
Edge Cases Handled
When k equals zero, the inner loop’s range becomes range(1, 1), which produces no iterations. Consequently, the accumulator have remains at its initial value of zero, and the method yields zero for every position. This behavior aligns with the specification that a zero key should result in a list of zeros.
Negative values of k are accommodated by the delta variable set to -1. The inner loop still iterates abs(k) times, but the position calculation uses a negative step, effectively moving backward through the list. The modulo operation guarantees correct wrap-around when the backward index would otherwise become negative.
The modulo operation also safeguards against indices that exceed the list bounds when k is larger than the list size. By reducing the computed position modulo size, the algorithm correctly cycles through the list multiple times if necessary.
Performance Optimizations
The code exhibits several micro-optimizations aimed at reducing overhead inside the nested loops. Storing len(code) in the local variable size prevents repeated attribute lookups, which can be costly in tight loops. The delta variable consolidates the direction decision into a single integer, allowing the inner loop to avoid branching on each iteration. Using the modulo operator for wrap-around eliminates the need for explicit conditional checks to reset the index when it reaches the list ends.
The choice of a generator (yield) instead of constructing a full result list provides a memory-efficient execution model. Consumers that only need to process elements sequentially can benefit from reduced allocation pressure, as the interpreter does not have to allocate a separate list to hold all results at once.
Overall, the implementation balances clarity with low-level efficiency, delivering correct behavior across all input variations while minimizing runtime overhead.
ELI5 - Simplified Explanation
Imagine a circle made of colorful blocks and each block has a secret number written on it. This set of instructions is like a game plan for a robot that walks around this circle to help you solve a puzzle.
First, the robot looks at how many blocks are in the circle. Then, it decides which direction to walk. If the magic number called k is positive, the robot walks forward. If the number is negative, the robot walks in the opposite direction.
The robot visits every single block in the circle one by one. When it stands on a block, it starts a little sub-game. It takes a certain number of steps forward or backward based on that magic number. Every time the robot lands on a block during those steps, it remembers the number written on it and adds it to a pile.
Once the robot finishes those steps, it holds the total sum for that specific block. Then it moves to the next block in the circle and does the exact same thing again until it has visited everyone. When the robot finishes playing this game at every spot, it has a brand new list of numbers that helps decode secret messages.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | Python | C++ | Java | TS | ||||||
| WalkCCC | Python | C++ | Java | ||||||||
| leetcode.ca | Python | C++ | Java | Go | TS | ||||||
| Progiez | Python | C++ | Java | ||||||||
| github | black-shadows | C++ | |||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| lkwq007 | Python | ||||||||||
| Shamik07 | Dart | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| lkwq007 | Python | ||||||||||
| Shamik07 | Dart | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 2490: Circular Sentence
- problem 2515: Shortest Distance to Target String in a Circular Array
- problem 2516: Take K of Each Character From Left and Right
Solved On The Same Day
- problem 1636: Sort Array by Increasing Frequency
- problem 1704: Determine if String Halves Are Alike
- problem 1725: Number Of Rectangles That Can Form The Largest Square
- problem 2305: Fair Distribution of Cookies
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality