Skip to content

Commit 161c151

Browse files
committed
Sync LeetCode submission Runtime - 86 ms (72.65%), Memory - 30.7 MB (7.59%)
1 parent b916b3c commit 161c151

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

0878-shifting-letters/README.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<p>You are given a string <code>s</code> of lowercase English letters and an integer array <code>shifts</code> of the same length.</p>
2+
3+
<p>Call the <code>shift()</code> of a letter, the next letter in the alphabet, (wrapping around so that <code>&#39;z&#39;</code> becomes <code>&#39;a&#39;</code>).</p>
4+
5+
<ul>
6+
<li>For example, <code>shift(&#39;a&#39;) = &#39;b&#39;</code>, <code>shift(&#39;t&#39;) = &#39;u&#39;</code>, and <code>shift(&#39;z&#39;) = &#39;a&#39;</code>.</li>
7+
</ul>
8+
9+
<p>Now for each <code>shifts[i] = x</code>, we want to shift the first <code>i + 1</code> letters of <code>s</code>, <code>x</code> times.</p>
10+
11+
<p>Return <em>the final string after all such shifts to s are applied</em>.</p>
12+
13+
<p>&nbsp;</p>
14+
<p><strong class="example">Example 1:</strong></p>
15+
16+
<pre>
17+
<strong>Input:</strong> s = &quot;abc&quot;, shifts = [3,5,9]
18+
<strong>Output:</strong> &quot;rpl&quot;
19+
<strong>Explanation:</strong> We start with &quot;abc&quot;.
20+
After shifting the first 1 letters of s by 3, we have &quot;dbc&quot;.
21+
After shifting the first 2 letters of s by 5, we have &quot;igc&quot;.
22+
After shifting the first 3 letters of s by 9, we have &quot;rpl&quot;, the answer.
23+
</pre>
24+
25+
<p><strong class="example">Example 2:</strong></p>
26+
27+
<pre>
28+
<strong>Input:</strong> s = &quot;aaa&quot;, shifts = [1,2,3]
29+
<strong>Output:</strong> &quot;gfd&quot;
30+
</pre>
31+
32+
<p>&nbsp;</p>
33+
<p><strong>Constraints:</strong></p>
34+
35+
<ul>
36+
<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>
37+
<li><code>s</code> consists of lowercase English letters.</li>
38+
<li><code>shifts.length == s.length</code></li>
39+
<li><code>0 &lt;= shifts[i] &lt;= 10<sup>9</sup></code></li>
40+
</ul>

0878-shifting-letters/solution.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Approach: Cumulative Sum (Prefix Sum)
2+
3+
# Time: O(n)
4+
# Space: O(n)
5+
6+
from itertools import accumulate
7+
8+
class Solution:
9+
def shiftingLetters(self, s: str, shifts: List[int]) -> str:
10+
s = list(s)
11+
12+
# Use accumulate to get cumulative shifts from right to left
13+
# We reverse the shifts array first, then reverse the result
14+
cum_shifts = list(accumulate(shifts[::-1]))[::-1]
15+
16+
for i in range(len(s)):
17+
new_char = chr((ord(s[i]) - ord('a') + cum_shifts[i]) % 26 + ord('a'))
18+
s[i] = new_char
19+
20+
return ''.join(s)
21+

0 commit comments

Comments
 (0)