-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
f25b6fe
commit 1464db0
Showing
2 changed files
with
40 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
38 changes: 38 additions & 0 deletions
38
2025-01-January-LeetCoding-Challenge/Shifting Letters II.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
from itertools import accumulate | ||
from typing import List | ||
|
||
|
||
class Solution: | ||
def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str: | ||
# line sweep algorithm | ||
line = [0] * (len(s) + 1) # account for shift after last element | ||
for start, end, direction in shifts: | ||
if direction == 1: | ||
# start shifting from start | ||
line[start] += 1 | ||
# stop shifting after end | ||
line[end + 1] -= 1 | ||
else: | ||
line[start] -= 1 | ||
line[end + 1] += 1 | ||
# prefix sum to calculate total shifts | ||
line = accumulate(line) | ||
|
||
result = '' | ||
for ch, sh in zip(s, line): | ||
result += chr(ord('a') + ((ord(ch) - ord('a') + sh) % 26)) | ||
return result | ||
|
||
|
||
def main(): | ||
s = 'abc' | ||
shifts = [[0, 1, 0], [1, 2, 1], [0, 2, 1]] | ||
assert Solution().shiftingLetters(s, shifts) == 'ace' | ||
|
||
s = 'dztz' | ||
shifts = [[0, 0, 0], [1, 1, 1]] | ||
assert Solution().shiftingLetters(s, shifts) == 'catz' | ||
|
||
|
||
if __name__ == '__main__': | ||
main() |