From 1464db0d1ac1cccecda5109b8a7956757c95b72e Mon Sep 17 00:00:00 2001 From: Siddhartha Dutta Date: Sun, 5 Jan 2025 00:25:07 +0000 Subject: [PATCH] Jan 5 --- .../README.md | 4 +- .../Shifting Letters II.py | 38 +++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 2025-01-January-LeetCoding-Challenge/Shifting Letters II.py diff --git a/2025-01-January-LeetCoding-Challenge/README.md b/2025-01-January-LeetCoding-Challenge/README.md index dad602d..80f98ea 100644 --- a/2025-01-January-LeetCoding-Challenge/README.md +++ b/2025-01-January-LeetCoding-Challenge/README.md @@ -7,7 +7,7 @@ | January 2 | [2559. Count Vowel Strings in Ranges](https://leetcode.com/problems/count-vowel-strings-in-ranges/) | Medium | Solved | | January 3 | [2270. Number of Ways to Split Array](https://leetcode.com/problems/number-of-ways-to-split-array/) | Medium | Solved | | January 4 | [1930. Unique Length-3 Palindromic Subsequences](https://leetcode.com/problems/unique-length-3-palindromic-subsequences/) | Medium | Solved | -| January 5 | []() | | | +| January 5 | [2381. Shifting Letters II](https://leetcode.com/problems/shifting-letters-ii/) | Medium | Solved | | January 6 | []() | | | | January 7 | []() | | | | January 8 | []() | | | @@ -40,5 +40,5 @@ | Level | Problems | Solved | Unsolved | | --- | --- | --- | --- | | Easy | 1 | 1 | 0 | -| Medium | 3 | 3 | 0 | +| Medium | 4 | 4 | 0 | | Hard | 0 | 0 | 0 | diff --git a/2025-01-January-LeetCoding-Challenge/Shifting Letters II.py b/2025-01-January-LeetCoding-Challenge/Shifting Letters II.py new file mode 100644 index 0000000..0fb47a4 --- /dev/null +++ b/2025-01-January-LeetCoding-Challenge/Shifting Letters II.py @@ -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()